作者:yafeilinux和他的朋友们
点击标题下「蓝色微信名」可快速关注
马上要过年了,咱们这次来做一个特别的,用粒子系统实现烟花效果。有的使用过Qt Quick粒子系统的小伙伴可能会说,一个爆炸效果有什么好做的,几行代码就实现了。但是如果要完整呈现烟花的发射爆炸整个过程,其实还是要费点功夫的,下面先来看效果图。
其实这个效果不是很好,建议大家看看下面的视频演示(有声音的哦)。
开发环境:Win 7 + Qt 5.12.0
首先实现发射效果
新建空的Qt Quick Application,完成后将main.qml文件内容更改如下:
import QtQuick 2.9 import QtQuick.Window 2.2 import QtQuick.Particles 2.12
Window { visible: true width: 800 height: 530 title: qsTr("Hello World")
color: "black"
ParticleSystem { id: particles anchors.fill: parent
ImageParticle { groups: ["stage1"] source: "qrc:///particleresources/star.png" alphaVariation: 0.4 colorVariation: 0.9 }
Emitter { id: burstEmitter x: 400 ; y: 480 group: "stage1" emitRate: 1; lifeSpan: 1500; size: 50; endSize: 10; sizeVariation: 30 acceleration: PointDirection {y: 100} velocity: AngleDirection{angle: 270; magnitude: 400; angleVariation: 40; magnitudeVariation: 50} } } }
这里我们创建了一个ImageParticle,然后使用发射器在上方一个弧度里面发射粒子,这样确保烟花是向上发射的。下面是运行效果。
添加一个冒烟小尾巴 为了实现烟花发射过程中留下的烟雾轨迹,我们使用TrailEmitter来实现这种跟随效果。在ParticleSystem对象中继续添加如下代码:
ImageParticle { groups: ["stage2"] source: "qrc:///particleresources/glowdot.png" color: "#11111111" }
TrailEmitter { group: "stage2"; follow: "stage1" emitRatePerParticle: 100; lifeSpan: 2400 lifeSpanVariation: 400 acceleration: PointDirection {y: -60 } velocity: AngleDirection{angle: 270; magnitude: 40; angleVariation: 22; magnitudeVariation: 5} size: 16; endSize: 0; sizeVariation: 8; }
下面是运行效果(睁大眼睛仔细看):
实现爆炸效果 烟花发射到空中是需要爆开的,下面添加爆炸效果:
ImageParticle { id: imageParticle groups: ["stage3"] source: "qrc:///particleresources/star.png" alpha: 0 colorVariation: 0.2 entryEffect: ImageParticle.Scale rotation: 60 rotationVariation: 30 rotationVelocity: 45 rotationVelocityVariation: 15 }
Emitter { id: burstEmitter2 group: "stage3" emitRate: 4000; lifeSpan: 3000; size: 30; endSize: 5; sizeVariation:10 enabled: false velocity: CumulativeDirection { AngleDirection {angleVariation: 360; magnitudeVariation: 80;} PointDirection {y: 20} } acceleration: PointDirection {y: 10 } }
不过这样添加的代码并不能让它在对应的点位爆炸,我们还需要进行一下特殊的处理来获取前面粒子发射到空中的位置,继续添加下面的代码:
Affector { system: particles width: parent.width height: 10; y: 90 once: true groups: "stage1" onAffectParticles: { for (var i=0; i<particles.length; i++) { burstEmitter2.burst(300, particles[i].x, particles[i].y); imageParticle.color = Qt.rgba(particles[i].red, particles[i].green, particles[i].blue, particles[i].alpha) } } }
这里使用了Affector影响器来获取发射过来的粒子位置,然后在这个位置进行爆炸,这样就实现了我们想要的效果,看看下面的动图,其实黑色背景也挺漂亮的。
化腐朽变神奇
很多时候腐朽离神奇只差一张背景图,如果还是不行,就再加上一个音效。我们在根对象Window中,ParticleSystem对象定义前添加如下代码:
SoundEffect { id:playSound source: "qrc:/sound.wav" }
Image { anchors.fill: parent source: "qrc:/back.jpg" }
然后在Affector的for语句最后添加一行代码来播放音效:
playSound.play()
现在可以运行程序查看效果了。
结语
谨以此程序祝愿所有支持yafeilinux的朋友们春节快乐!
如果需要下载源码,可以点击下面的阅读原文到社区进行下载。
------------------------------------------------------------------------- 我们尊重原创,也注重分享,如若侵权请联系qter@qter.org。 -------------------------------------------------------------------------
|