Swift: Create a Beautiful Star Trail Using a Particle Emitter

With a simple UIPanGestureRecognizer implementation

Zafar Ivaev
Feb 7 · 2 min read
Star icon by Icons8

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.

Let’s Start

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:

  • birthRate defines the number of particles emitted per second.
  • lifetime defines the number of seconds a particle will be visible on the screen.
  • velocity defines the initial velocity of the particle.
  • velocityRange describes the amount by which the velocity can vary.
  • emissionLongitude defines the angle of emission.
  • emissionRange defines the amount by which the angle of emission can vary.
  • spinRange defines the amount by which the spin of the particle can vary.
  • scale applies magnification to the particle.
  • scaleRange defines the range of the magnification.
  • alphaSpeed is the amount by which the particle’s alpha property will change over its lifetime.
  • contents describes the image for the particle. In our case, it is a star icon.

Adding the StarParticle

let starParticle = StarParticle()

We need to create a CAEmitterLayer now and append the starParticle to its emitterCells array property inside the showStars() method:

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 SceneView:

All that’s left is the missing handleTap() method:

Finally, we can run our Playground, click and move the cursor on the SceneView, and see stars being emitted:

Thanks for reading!

Better Programming

Advice for programmers.

Thanks to Zack Shapiro

Zafar Ivaev

Written by

👨🏻‍💻 iOS & Flutter Developer

Better Programming

Advice for programmers.

More From Medium

More from Better Programming

More from Better Programming

More from Better Programming

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade