Quantcast
Channel: Kodeco | High quality programming tutorials: iOS, Android, Swift, Kotlin, Unity, and more
Viewing all articles
Browse latest Browse all 4399

Introduction To Unity: Particle Systems

$
0
0
Note: This tutorial is part of the Unity Feast. To see more tutorials being featured in the Unity Feast as well as to learn how to take part in the Unity Feast game jam, click over here.
Make particle effects like these!

Make particle effects like these!

Particles effects are like salt; just a small amount can add extra “pizzazz” to whatever you’re cooking up. Modern games that don’t use particle effects in some manner feel can quite bland.

Particles also add authenticity to scenes. They can be the foundation of a roaring campfire, or the luminous effects of a wizard’s spells. They can also be used to create smoke, dust, explosions, and even rainbow puke! :]

In essence, particles are small, simple images or meshes that are emitted and then manipulated by a particle system during their lifetime.

Back in the old days, you needed to know the black arts of graphics programming to make even a wisp of smoke. Thankfully, Unity makes creating particle systems quite simple. Unity uses a powerful, modular built-in particle system named Shuriken, which is quite easy to learn but also lets you create complex effects – once you get to know it.

In this tutorial you’ll learn the following:

  • How to add a new particle system in Unity.
  • What the most commonly used particle system modules do and how to use them.

Time to get started!

Note: This tutorial assumes you understand the basics of working with Unity. If you are new to Unity, or need a refresher, please see our Introduction to Unity tutorial.

Getting Started

Download the particle system starter project and extract it to a convenient location. You’ll use this as your starting point.

This tutorial has two main parts; in the first, you’ll build the flames of a torch, while in the second part you’ll create a bomb explosion effect.

Open up the Starter Project in Unity. The assets inside are sorted into several folders:

  • Materials: Holds the fire material.
  • Models: Contains the torch and bomb models and their materials.
  • Prefabs: Hold the bomb prefab.
  • Scenes: Contains the Torch and Bomb scenes.
  • Scripts: Holds the initial scripts.
  • Textures: Contains the texture for the fire material.

Adding a Particle System

A particle system generally emits particles in random positions within a predefined space, which can be shaped like a sphere or a cone. The system determines the lifetime of the particle itself, and when that lifetime expires, destroys the particle.

Once nice thing about particle systems is that they are components that you can add to any GameObject in the scene. Want to have your sharks emit lasers from their eyes? Simply add a particle system to the eye GameObject, and your sharks will be unstoppable! :]

Open up the Torch scene in from your Project Window and run the scene:

There’s not much going on at the moment. The torch hangs on the wall, but there’s no fire to be seen. You’ll need to add a particle system first.

Select TorchFireParticles inside the Hierarchy. Inside the Inspector, click the Add Component button. Search for Particle System and click to add it:

Screen Shot 2015-10-29 at 2.55.44 PM

Note: You might have noticed you didn’t add the particle system directly to the Torch GameObject. This is because the particles would be emitted from the middle of the torch, instead of from the fuel container at the top.

Play your scene; you’ll see you have particles emitting already:

True, it doesn’t look much like fire, but you’ll fix that shortly. But first, you’ll need to understand the current state of the particle system and how to change it.

Note: When you select a GameObject with an attached particle system, you’ll notice a black dialog in the lower right hand corner of the scene view. This dialog gives you the ability to simulate or stop the particle system. Clicking Simulate activates your particle system and changes the button to a “Pause” button. To stop the simulation, click the “Stop” button.

Screen Shot 2015-10-29 at 3.05.52 PM

This dialog is useful for designing particle systems that run on a fixed timeline, such as explosions.

A Closer Look at a Particle System

Take a look at the Inspector; you’ll notice the particle system Component you added has several sub-sections:

Each of these sub-sections is called a Module. These Modules contain the settings for the particle system. The Module expanded by default is known as the Main module:

The Main module is the meat and bones of any particle system in Unity, and the most common particle settings live here:

  • Duration: The length of time in seconds for the particle to run. Leave this at the default value of 5.00.
  • Looping: Repeatedly emit particles until the particle system stops. The cycle restarts once the Duration time is reached.
    Left: on Right: off

    On & off

    The fire needs to burn continuously, so leave this enabled.

  • Prewarm: Only used when Looping is enabled. The Particle System will act as if it’s already completed a full cycle on start-up.
    On & off

    On & off

    For your fire effect, leave this disabled to make it look like the torch was just ignited.

  • Start Delay: The delay in seconds before the particle system start emitting. Leave this at the default value of 0.
  • Start Lifetime: The initial lifetime in seconds for the particles. The particle is destroyed after this elapsed time.
    Top: 8 seconds Bottom: 3 seconds

    Top: 8 seconds
    Bottom: 3 seconds

    Set the lifetime to 1.2 seconds; this ensures the flame won’t be too tall.

  • Start Speed: The initial speed of the particles. The greater the speed of the particles, the more spread out they will be.
    Top: 2 Bottom: 10

    Top: 2
    Bottom: 10

    Set the speed to 0.75; this will make the fire effect slower and more dense.

Note: When you modify the settings of the particle system, you’ll see a preview of it in the Game Window. Keep an eye on this preview while following along. You’re also free to experiment with the values on your own to learn more about how each setting affects your system.

Before continuing, run your scene to see the effect of your changes:

The effect looks pretty cool already, but it looks a lot like steam, smoke or plasma — and less like actual fire. Admire what you’ve done for a moment, and then get ready for the next batch of Main module settings! :]

More Main Module Properties

You’ve set up the torch, but the fire effect still leaves a lot to be desired. Thankfully, the Main module has additional options to further refine the shape and behavior of your torch.

Select the TorchFireParticles GameObject in the Hierarchy and scroll down to the particle system, if it isn’t already open. Under the Main Module, take a look at the following properties:

  • Start Size: the initial size of the particles.
    Top: 0.2 Bottom: 1

    Top: 0.2
    Bottom: 1

    Set the size to 0.25; this is a manageable size that lets you see the individual particles more clearly.

  • Start Rotation: The initial rotation angle of the particles.
    Top: 0° Bottom: 45°

    Top: 0°
    Bottom: 45°

    Keep the rotation at ; the particles are round so you will hardly notice the difference.

  • Start Color: The initial color of the particles. Keep the color at the default value of pure white (255,255,255); you’ll color the fire via a texture.
  • Gravity Modifier: Scales the gravity value set in Unity’s Physics Manager window. If it’s set to 0, the gravity will be turned off.


    The image above is from a system with the gravity modifier set to 1, which makes the particles flow down like a waterfall. Leave the gravity in your system at 0; the particles will move upwards with the velocity you set in Start Speed.

  • Inherit Velocity: Starts particles with the same velocity as the particle system. This only works if the particle system has a Rigidbody attached.
    Left: 1 Right: 0

    Left: 1
    Right: 0

    Keep Inherit Velocity at 0; you don’t need this for the fire effect.

  • Simulation Space: Moves particles in Local Space along with the particle system; while in World Space, particles move freely once emitted.
    Top: local space Bottom: world space

    Top: local space
    Bottom: world space

    Leave your simulation set to Local Space. The effect will only be visible once the particle system is moved.

  • Play On Awake: Starts emitting immediately when enabled. If this is turned off, you have to manually start the particle system via script or an animation system. Leave this setting on, as you want the fire to start when the scene starts playing.
  • Max Particles: The maximum amount of particles the particle system is allowed to have alive at any time. If you try to emit more particles than this once the system hits this limit, they won’t be emitted at all. This setting is used primarily for performance reasons; the default value of 1000 particles is more than enough in this case.

Whew, that was quite a list! But as a result, you’ve learned how to add a particle system to your scene and how to customize it to your liking.

Run your scene again to see the effect of your changes:

It looks a bit more like fire every time, doesn’t it? It needs more particles though, and to do that, you change the emission of the system.

Introducing the Emission Module

The Emission module is one of the most important modules in Unity particle systems; it handles the number and timing of emitted particles in the system to create a continuous flow or a sudden burst of particles depending on your needs.

While still in the particle system’s Inspector, click on the Emission module title:

This opens up the Emission module:

The Rate is the number of particles emitted per second (Time), or alternatively, per unit (Distance). You can switch between the two modes by clicking the combo box and selecting the desired mode:

Leave the settings at Time and change the Rate to 50.

Run your scene again; it looks a lot more lively now:

Yeah, it still looks like smoke. But here comes the biggest change so far in this tutorial: a custom texture!

Adding a Custom Texture

All particles have a particle material and a texture that defines how they look. There’s only so much you can do with the default texture. By changing the texture you can create effects like magic stars, smoke and of course, fire.

Changing the particle texture is quite easy. Up to now, the particles were drawn on the screen using the Default-Particle material, which is a particle material with a circular gradient texture:

To change the material, select the TorchFireParticles GameObject inside the Hierarchy. Then, find the the particle system component in the Inspector, and open up the particle system’s Renderer module.

Open the Materials folder in the Project View, and drag the FireMaterial Material to the Material property:

Finally, run the scene to see your custom texture in use:

Can’t you almost feel the heat? :] The flame’s a bit too wide though; to fix that, you’ll have to change the shape of the particle system.

Changing the Particle System’s Shape

The Shape module, as the name implies, controls the shape and the behavior of particles in that shape. You can choose from several different shapes; each has their own particular settings. This lets you create particles in a box, a sphere, or even in your own custom mesh!

Expand the Shape module in the Inspector:

The shape of your particle system is set to cone, which means particles emit from the base and are moved outwards at an angle:

In the example above the base is colored blue, the angle is green and the particles are red. Also notice that while you have the Shape Module expanded, you’re presented with a handy preview of the cone in the Scene view:

Changing the Angle changes the size of the cone to make it wider or narrower. Set this to 10; you’ll get a nice tight flame that widens slightly as the particles rise.

Changing the Radius changes the size of the base; the larger this value is, the more the particles will scatter as they emit. Set this value to 0.2; this ensures the flames will start inside the fuel holder of the torch.

Run your scene and see how the shape of the flame has changed:

That’s starting to look like a real flame! The finishing touch is to change the size of the particles over the course of their lifetime.

Changing Size Over Lifetime

With the Size over Lifetime module, you can create particles that grow or shrink during their lifetime, or even pulsate like fireflies in a forest.

In your particle system’s module list, look for “Size over Lifetime“. Contrary to the previous modules, Size over Lifetime isn’t enabled by default. Click on the checkbox next to the module name to enable it:

Expand the Size over Lifetime module by clicking on its name. This will display a dark gray background with a flat Curve running along the top:

Click on the dark gray background to open the curves editor at the bottom of the Inspector. The horizontal axis depicts the lifetime of the particle while the vertical axis depicts its size:

You can move the keys at either end of the red line to edit the curve; you can also add additional keys by double-clicking anywhere on the curve. To delete keys, right-click on the key to remove and select Delete Key:

You can also select one of the preset curves at the bottom:

If you think about flames in the real world, they tend to shrink as the particles rise, so select the third preset from the right to create a downwards slope:

Run your scene to see your effect in all its fiery glory!

If you’ve worked in a basic form with Animations, see if you can figure out how to add flickering shadows!

Solution Inside: How to create flickering shadows? SelectShow>

Congratulations! You’ve learned how to set up a new particle system and bend it to your will to make a beautiful fire effect. Take a break, get something to drink or eat to celebrate, then come back and let your inner Michael Bay shine as you learn to create explosion effects!

Building a Bomb (Effect)

Making an exploding bomb is quite simple using Unity. Once you know how to instantiate particles at will, you can use this effect for things such as car wheels sparking when they scrape the ground, or balloons that pop and shower confetti.

Open up the Bomb scene from the Project Window and play the scene:

There’s a floor at the bottom of the scene, but apart from that, there’s not much going on at the moment.

To spawn bombs, drag the Bomb Prefab to the Bomb Emitter:

DragBombPrefabToEmitter

Play the scene again to see your bombs appear:

The emitter creates a new bomb every 2 seconds. To put a neat spin on things, you’ll add some rotational force to the bomb when it spawns.

Open up the Bomb script inside the Scripts folder in your Project Window.

Add the following code to Start():

void Start() {
  float randomX = UnityEngine.Random.Range (10f, 100f);
  float randomY = UnityEngine.Random.Range (10f, 100f);
  float randomZ = UnityEngine.Random.Range (10f, 100f);
 
  Rigidbody bomb = GetComponent<Rigidbody> ();
  bomb.AddTorque (randomX, randomY, randomZ);
}

The first three lines generate random float values between 10 and 100 for the x, y and z axes. Next, you get a reference to the bomb’s Rigidbody component and apply torque to it. This causes the bomb to rotate in a random direction:

The bombs now rotate nicely while they fall — but you were promised explosions! Don’t worry; you’ll add that now. :]

In the Hierarchy, press the Create button and select Create Empty. Click on the newly created GameObject and name it ExplosionParticles. Next, add a new particle system to the GameObject. If you’ve forgotten how to create a particle system, scroll on up for a refresher.

With your particle system in place, drag the ExplosionParticles GameObject from the Hierarchy to the Prefabs folder in the Project Browser. Next, select the Bomb Prefab inside the Prefabs folder. Finally, drag the ExplosionParticles Prefab to the Bomb‘s Explosion Particles Prefab slot like so:

Now, when a bomb touches the ground a new Explosion Particles GameObject will spawn.

Play your scene to see how the explosion looks:

Very…uh…magical, but nothing near an explosion yet! Also notice there’s already an ExplosionParticles GameObject present in the scene at the start. Delete the ExplosionParticles GameObject in the Hierarchy; from now on you’ll be editing the prefab.

As with the torch, you’ll be using the fire material for the particle system.

Select the ExplosionParticles Prefab in the Project Window, then expand the Renderer Module in the Inspector. Drag the FireMaterial from the Materials folder in the Project Window to the Material slot as shown below:

To complete the effect, you’ll have to modify the following settings in the Main module:

ExplosionMainModule

  1. Set the Duration to 0.70.
  2. Looping should be disabled. The particles should emit just once.
  3. Set the Start Lifetime to 0.7.
  4. Set the Start Speed to 10.
  5. Set Start Size to 2.
  6. Set the Gravity Modifier to 1. This will make the particles drop slightly at the end.

Run your bomb scene to see what you’ve built:

Well, it’s kind of explod-y, but you can definitely do better!

Building the Explosion

To improve the explosion, you’ll alter the properties of one particle system’s modules. Can you guess which module to alter? Here’s a hint — you’ve already used it.

If you guessed the Emission module, give yourself a pat on the back!

Expand the Emission Module; as you saw earlier, the Rate is the number of particles spawned per second. For this explosion, you won’t want a steady flow of particles, but rather a sudden burst.

Set the Rate to 0. Now take a look beneath the Rate; there’s a list of Bursts that’s empty by default:

A Burst is a collection of particles emitted all at once at a particular point in time.

Click on the + button at the bottom right to add a new Burst. You’ll see two fields: Time & Particles:

Leave the Time at 0, and set Particles to 150.

These settings will make the particle system emit 150 particles all at once at the start of the system.

Play your scene; how do things look now?

Now THAT looks more like an explosion! While this explosion looks better, the shape is still an awkward cone and the particles don’t fade out — they just disappear. You’ll need to mold your explosion to give it that final touch.

To get started, expand the Shape Module:

You’ve already used this module for the torch’s fire shape, but there are several more shapes to choose from. Click on the dropdown box that says Cone to see all options available to you:

Each shape affects the emitter in a different way. Each animation below shows the same emitter, with only the shape changed:

Sphere

HemiSphere

Cone

Box

Mesh (Cube)

Circle


Edge

You can get lots of different effects from the same system — just by changing the shape!

To create a realistic explosion, set the shape to Sphere.

Run the scene and prepare to be blown away:

Now that looks awesome! :]

While the explosion looks good, there’s one small problem. The particles just disappear. This is a jarring effect and doesn’t look natural at all. Rather than just disappear, the particles should disappear over time to make the explosion fade away.

Changing Color

With the particle system open in the Inspector, click the checkbox next the Color over Lifetime module to enable it and expand it. You’ll be greeted by the word Color and what looks like a white block next to it. Click on the white block:

Screen Shot 2015-10-30 at 2.16.41 PM

This opens up the gradient editor:

The color change over the lifetime of the particles is represented as a gradient bar. The starting color is on the far left, and the particles will transition to the color on the right side:

The four white arrows at the edges are known as markers; click between two existing markers to add a new one. To remove a marker, drag it off the bar:

The top markers handle the Alpha or opacity of the color, while the bottom markers manage the RGB (Red, Green, Blue) color values.

Click on the rightmost alpha marker. The bottom of the Gradient editor now shows the current alpha value:

Drag the slider all the way to 0. Now the particles will gradually fade away over the course of their lifetime.

Run your scene once again to see the effect of your changes:

Yeah baby — that’s one hot explosion!

Want extra credit? Return to the torch scene and configure the flame to use Size Over Lifetime Module to achieve a similar effect.

Where to Go From Here?

You can download the final project here.

In this tutorial, you’ve learned how particle systems and its various modules work in Unity, and how to tweak them to get exactly the effect you want. Feel free to experiment with the different settings to see what other cool effects you can achieve.

For more information on the Shuriken Particle System and its modules, take a look at Unity’s official documentation and their Particle System video.

I hope you enjoyed this tutorial; if you have any comments or questions, please share them in the discussion below!

The post Introduction To Unity: Particle Systems appeared first on Ray Wenderlich.


Viewing all articles
Browse latest Browse all 4399

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>