Swift: Create a Beautiful Star Trail Using a Particle Emitter
With a simple UIPanGestureRecognizer implementation
In this short tutorial we will learn how to create a star trail in Swift. We will use an Xcode Playground because it’s a nice way to quickly build and test things.
The source code of the project is available on GitHub.
First, we need to create a base
UIView where the animation will take place:
We need to set
PlaygroundPage.current.liveView = SceneView() to be able to see the live view when tapping on the blue “Play” button.
Now let’s create our star particle:
Here’s a description of each property:
birthRatedefines the number of particles emitted per second.
lifetimedefines the number of seconds a particle will be visible on the screen.
velocitydefines the initial velocity of the particle.
velocityRangedescribes the amount by which the velocity can vary.
emissionLongitudedefines the angle of emission.
emissionRangedefines the amount by which the angle of emission can vary.
spinRangedefines the amount by which the spin of the particle can vary.
scaleapplies magnification to the particle.
scaleRangedefines the range of the magnification.
alphaSpeedis the amount by which the particle’s alpha property will change over its lifetime.
contentsdescribes the image for the particle. In our case, it is a star icon.
Adding the StarParticle
starParticle property to the
let starParticle = StarParticle()
We need to create a
CAEmitterLayer now and append the
starParticle to its
emitterCells array property inside the
We’ve implemented our star particle emitter. Now we need to emit stars based on the pan gesture. Let’s create a
UIPanGestureRecognizer and add it to the
All that’s left is the missing
Finally, we can run our
Playground, click and move the cursor on the
SceneView, and see stars being emitted:
Thanks for reading!