Chapter 4: Applying Art, Animation, and Particles

In this chapter, we'll apply several art effects to the player's ship and the scene that we imported back in Chapter 2, Adding and Manipulating Objects. We will use several maps that wrap around your player's ship to give it a sci-fi theme, including some pretty particle effects that we will add to our neon-blue jet. We will also introduce a space background, which will also be built from particle effects. Then, you will get your hands dirty by setting up your own Unity Animator Controller, which we can use to manipulate the particles we've created in our scene to give the impression that our player's ship is thundering through space at lightspeed, then slowing down before the enemies come to attack. Finally, we will apply some animation to the enemies in our script.

A lot of this chapter is about becoming familiar with what Unity can do as an Editor and the majority of what we learn in the Editor is also possible to achieve through code. This is why, as a programmer, it's important to know what we can manipulate in a project.

In short, we will be covering the following topics:

  • Adding visuals to the player's ship
  • Creating a particle effect
  • Importing and animating scenery
  • Animating three-dimensional enemies with a script

So, let's jump in and make a start on changing the appearance of the player's ship.

The core exam skills covered in this chapter

We will look at programming core interactions:

  • Implementing and configuring game object behavior and physics

We will also look at working in the art pipeline:

  • Understanding materials, textures, and shaders, and writing scripts that interact with Unity's rendering API
  • Understanding lighting and writing scripts that interact with Unity's lighting API
  • Understanding two-dimensional and three-dimensional animation and writing scripts that interact with Unity's animation API
  • Understanding particle systems and effects and writing scripts that interact with Unity's particle system API

We will cover the programming for scene and environment design:

  • Identifying methods for implementing game object instantiation, destruction, and management

Finally, we will cover working in professional software development teams:

  • Recognizing techniques for structuring scripts for modularity, readability, and reusability

Technical requirements

The project content for this chapter can be found at https://github.com/PacktPublishing/Unity-Certified-Programmer-Exam-Guide-Second-Edition/tree/main/Chapter_04.

You can download the entirety of each chapter's project files at https://github.com/PacktPublishing/Unity-Certified-Programmer-Exam-Guide-Second-Edition.

All the content for this chapter is held in the chapter's unitypackage file, including a Complete folder that holds all of the work we'll carry out in this chapter.

Check out the following video to see the Code in Action: https://bit.ly/3OHV4xi.

Adding visuals to the player's ship prefab

In this section, we will focus on the player's ship. We'll create a series of different visual art techniques to make our ship look futuristic without physically changing its geometry. We will create and apply a type of material to our ship that is used as housing to hold and display several maps. These maps are responsible for targeting specific channels on our player's ship. Because this book is specifically for programmers, I have created several of these maps that you can drag and drop into the material component that sits within the Inspector window.

Normally, if a three-dimensional model, such as the player's ship, has a texture applied to it, the model needs to undergo a method called unwrapping. Unwrapping is like peeling off the faces of the model and laying them down flat so that they can have textures applied to them. Then, the unpeeled faces are wrapped back around the three-dimensional model. If the model isn't unwrapped before we apply the texture, the texture of the ship will be scrambled as it doesn't know where it should display the textures correctly. We don't need to go any further into the details of unwrapping as it's beyond the scope of this book, but just remember that the player's ship model has to be unwrapped.

The following screenshot shows the three-dimensional model of our player's ship on the left and its unwrapped version, which is textured, on the right:

Figure 4.1 – Player Ship 3D model and its UV map

Figure 4.1 – Player Ship 3D model and its UV map

We will also be shining a colored light onto the ship, but only allowing certain parts of it to emit and ensuring the light doesn't shine on any other game object with Unity's layer system. The other major part of Unity that we will cover is the particle system; we will create our own particle jet that will animate from the rear of the ship.

The following screenshot shows what our player's ship looks like currently on the left. By the end of this section, we will have a sci-fi-looking ship with an animated jet, shown on the right side of the screenshot:

Figure 4.2 – The player's ship will be textured and carry its own thruster particle effect in this chapter

Figure 4.2 – The player's ship will be textured and carry its own thruster particle effect in this chapter

Let's now move on to creating a material that can be used to store the maps from this chapter's unitypackage download that is on GitHub.

Creating a material for our player's ship prefab

Currently, our player's ship has a default material applied to it, which we can't edit in the Unity Editor. To be able to change the ship's color and apply several maps, we first need to create a material and then apply it to the player's ship. To do this, follow these steps:

  1. In the Project window, navigate to Assets/Material/Player and right-click in an open space.
  2. Left-click on Create at the top.
  3. Then, left-click on Material.
  4. A material icon will appear, highlighted in blue. Rename this material PlayerShip.

    Tip

    To rename a material when it isn't selected, left-click on the text below the icon twice to bring the blue highlight back up. Then, enter a name—in our case, PlayerShip. For Mac, hit Enter on the selected material and start typing its name to rename it.

The following screenshot shows how the material is created:

Figure 4.3 – Creating a material in the Unity editor

Figure 4.3 – Creating a material in the Unity Editor

There are two ways to apply a material to the ship. The first and easiest way is to drag and drop the material to the PlayerShip model in the Scene view.

Tip

A material can be created and updated in the script through the Renderer.material property. Check out https://docs.unity3d.com/ScriptReference/Renderer-material.html to find out more.

The second—and probably the better—way, as it's a more controlled method in updating a material, is to select PlayerShip in the Scene window or select PlayerShip from its prefab folder. Then, in the Inspector window, do the following:

  1. Next to the Mesh Renderer component is the Materials drop-down arrow. Click on the arrow so that it points downward.
  2. The two main points to look for within the component are the following:
    • Size: How many materials are attached to this model. This should be set to 1.
    • Element 0: This is the material that is currently attached, Default-Material.
  3. Either click on the small button to the far right of Default-Material (or whatever the material is called), as in the following screenshot, or drag and drop the PlayerShip material we just made into the same location as Default-Material.

The following screenshot shows the location of the Mesh Renderer component situated within the Inspector window:

Figure 4.4 – Player_Ship Mesh Renderer location in the Inspector window

Figure 4.4 – player_ship Mesh Renderer location in the Inspector window

Once that's done, Element 0 will be updated to PlayerShip, Size will remain as 1, and Default-Material at the bottom of the Inspector window will now be editable and named PlayerShip (or whatever you named the material).

Tip

Default-Material cannot be edited as it is typically shared with new Mesh Renderer game objects.

Now, we need to update the ship's prefab (prefabs were explained in Chapter 1, Setting Up and Structuring Our Project). If the PlayerShip model is still selected, go to the Inspector window and click on the Apply button in the top-right corner. If you made changes directly to PlayerShip from the Prefab folder, this will not be necessary as we have updated the prefab directly. In the next section, we will break down the various maps we can now apply to the material.

Applying maps to our PlayerShip material

Our newly created material for our PlayerShip prefab is now able to hold various maps. Our material will have empty slots for each map; these maps will add details to the player's ship, ranging from the color to fake details, such as cuts, dents, and grooves, that aren't physically modeled into the player's ship. We can also emphasize where the light will be absorbed by the player's ship.

Here is a selection of maps that we will apply to the PlayerShip prefab:

  • Albedo map (playerShip_diff): The albedo map contains the color of the image, which is similar to a diffuse map but without light and shadow. The following screenshot shows our albedo map:
Figure 4.5 – PlayerShip albedo map

Figure 4.5 – PlayerShip albedo map

  • Metallic map (playerShip_met): The metallic map focuses on the reflectivity and light of the surface. The following screenshot shows our metallic map:
Figure 4.6 – PlayerShip metallic map

Figure 4.6 – PlayerShip metallic map

  • Emissive map (playerShip_em): The emissive map receives no light, and is ideal for a glow-in-the-dark effect (self-illuminating). The following screenshot shows our emissive map:
Figure 4.7 – PlayerShip emissive map

Figure 4.7 – PlayerShip emissive map

  • Normal map (playerShip_nrm): The normal map stores the direction of each pixel. The general use for this map is holding high-resolution details that give the illusion of more polygons in a mesh. The following screenshot shows our normal map:
Figure 4.8 – PlayerShip normal map

Figure 4.8 – PlayerShip normal map

  • Occlusion map (playerShip_oc): The occlusion map provides information on which areas of the model receive light. The following screenshot shows our occlusion map:
Figure 4.9 – PlayerShip occlusion map

Figure 4.9 – PlayerShip occlusion map

Now, we will apply these maps to the PlayerShip model by taking the following steps:

  1. Select the player_ship game object, which can be selected in either the Scene or in the Project window (under the Assets/Prefab/Player file path location).
  2. To make things easier when applying our maps to the player_ship material slots, lock the Inspector window while we still have player_ship selected at the top of the Inspector window, as in the following screenshot (make sure you unlock the Inspector window once you've finished dragging and dropping files over):
Figure 4.10 – Locking the Inspector window

Figure 4.10 – Locking the Inspector window

  1. In the Project window, we can drag and drop each map file from the newly imported Texture folder into the PlayerShip material component slots.

Before we drag and drop the files into their designated boxes, be sure that your normal and emission maps are set up correctly. Let's start with the normal map.

When it comes to applying a normal map, there are some extra procedures to cover. The first is that Unity may not recognize Normal Map as a normal map file. When we drag and drop the normal map file into its slot in the Material component, as in the previous screenshot, an information box appears in the Inspector window under the Normal Map slot. This contains a message (This texture is not marked as a normal map) with a Fix Now button. Click on this button so that the normal map is configured correctly. The following screenshot shows what the information box looks like:

Figure 4.11 – Fixing normal maps

Figure 4.11 – Fixing normal maps

Another way of fixing this issue with the normal map is by doing the following:

  1. Select the normal map file in the Project window.
  2. Then, in the Inspector window, we have a panel showing the normal map's Import Settings option.
  3. At the top of the options area, click on the dropdown next to Texture Type and make sure it is selected as a Normal Map.
  4. Finally, click on Apply at the lower-right corner of the Inspector window.

The following screenshot shows a normal map file selected from the Texture Type dropdown and the Normal map selection in the dropdown:

Figure 4.12 –Texture Type set to Normal map

Figure 4.12 –Texture Type set to Normal map

Another potential issue when dragging and dropping maps into the Material component is that you need to check the box next to the Emission slot before it can accept a map. The following screenshot highlights the Emission slot and shows you the box that needs to be checked:

Figure 4.13 – Emission check box checked

Figure 4.13 – Emission check box checked

Great, now we know the possible issues, we can drag and drop out files into their designated boxes.

Navigate to the Project window and in the Assets/Texture folder drag and drop each of the files into their correct slots:

Figure 4.14 – Drag and dropping maps into the Player Ship material correct slots

Figure 4.14 – Drag and dropping maps into the Player Ship material correct slots

Further Information

The material properties, such as the emission color, can be made and altered via script with the use of the SetColor property. For more information on changing a material's color or emission color, check out https://docs.unity3d.com/ScriptReference/Material.SetColor.html.

Once we have dragged and dropped all the maps into their designated slots, our player_ship model should look different as it now has a metallic complexion. However, we aren't finished yet. We need to add some neon lights to the ship next.

Adding neon lights to our PlayerShip prefab

Our ship currently looks like metal, slightly dull with some sci-fi-style patterns on it. As this isn't an art exam, our preliminary mission isn't to make this ship look fantastic, but rather to understand the maps and effects that we're adding to it. As mentioned briefly in the previous section, we can add some light to the ship that will also react to the ship's maps. The following screenshot shows what our ship currently looks like with all the maps applied; yours may be shiny, but that doesn't matter:

Figure 4.15 – Player Ship with all maps applied

Figure 4.15 – Player Ship with all maps applied

Next, we are going to make parts of the ship light up in a sci-fi neon-blue color, combining a Point light with the emissive map.

To add a light to our ship, we need to do the following:

  1. From the Project window, navigate to Assets/Prefab/Player.
  2. Select player_ship and drag it to the Hierarchy window.
  3. Click on the Add Component button in the Inspector window and type Light into the dropdown.
  4. When you see the Light component in the drop-down list, select it.

    Tip

    If the Scene window is too far away from the ship, select player_ship from the Hierarchy window, hover your mouse in the Scene window, and press F on your keyboard to zoom in.

This Point light will act as a glow around the ship that will affect only the player's ship and the emissive map with Unity's layer system. But first, we will focus on the Light component settings in the Inspector window:

Figure 4.16 – player_ship's Light component property values

Figure 4.16 – player_ship's Light component property values

With the Point light selected from the Hierarchy window, we can alter our new light settings in the Inspector window:

  • Type (Point): At this stage, we can change the type of light without having to delete the light and add a new type. For this instance, we want a Point light. The player_ship will also have a yellow gizmo wrapped around it to represent the size of the light as shown in the following screenshot:
Figure 4.17 – Light gizmo surrounding the player_ship

Figure 4.17 – Light gizmo surrounding the player_ship

Tip

A gizmo is an indicator that shows up in the Scene window, which you will not see in the Gam window. A gizmo is displayed as guidance to show the location and/or the scale of something.

  • Range (50): The range will increase/decrease the size of the yellow sphere, pushing the light out more. I have set mine to 50 as I feel this covers the ship well enough.
  • Color (blue): I have gone for a light-blue color, but you can pick whatever color you wish to. If you want to use the same color as mine, do the following:
    1. Click on the current Color bar and the Color window will appear.
    2. At the bottom of the settings window, change the Hex Color value to 0080FFFF. (This will set the red, green, blue, and alpha settings.)
  • Intensity (10): The strength of the light.
  • Indirect Multiplier (0): The light bouncing onto other objects. Real-time indirect bounce shadowing is not supported for the Point light.
  • Render Mode (Important): Makes sure the light remains on at all times and doesn't turn off with performance drops.
  • Culling Mask (PlayerShip): We will talk about this next. We are using a blue light (in my case) to give the maps on the ship a neon light effect. We ideally don't want the light to spread onto other assets if they come near the player's ship.

    Important Note

    Play around with the Light component; don't feel like it has to have the exact same color or intensity as mine.

Once these settings (apart from the culling mask) for our light have been updated in the Inspector window, our ship should have neon lights lit across it in various areas. In the following screenshot, I have placed eight spheres behind the player ship model. Notice now how our new neon light clashes against the spheres. I'll explain how we can fix the issue of the light clashing with other objects in our game next:

Figure 4.18 – The player ship's light clashing with near 3D objects

Figure 4.18 – The player ship's light clashing with near 3D objects

A culling mask will fix this issue as we can make the blue light only display on the player's ship with a specific layer mask.

To make a new layer, we need to go to the Tags & Layers section, which can be accessed in two ways:

  1. The first way is by clicking on the Layers tab at the top right of the screen in the toolbar section. A dropdown will appear with the available layers. Click on the bottom option, Edit Layers....
  2. The second way is by selecting any game object in the Hierarchy window and clicking on the tab next to Layer. Then, click on the bottom option, Add Layer...:
Figure 4.19 – Adding a new layer

Figure 4.19 – Adding a new layer

The Tags & Layers panel will appear within the Inspector window with grayed-out layers that cannot be edited as they are built in. Also, it is recommended that you don't use layer 31 as it has an internal use for the Editor.

  1. Layers 8 to 30 are okay to use. I'm going to enter PlayerShip into the User Layer 8 field, as in the following screenshot:
Figure 4.20 – Adding a layer named PlayerShip

Figure 4.20 – Adding a layer named PlayerShip

  1. Now, click on the player_ship GameObject in the scene or within the Prefab folder and change its point light Culling Mask option from Everything to PlayerShip:
Figure 4.21 – PlayerShip layer in the drop-down list

Figure 4.21 – PlayerShip layer in the drop-down list

  1. Then, select the player_ship model from Hierarchy.
  2. In the player_ship Inspector window, change its layer to our newly created layer, PlayerShip. Because we added a Point light to our player's ship, we are given a warning asking us whether we want to change the children within the player_ship model.
  3. Click Yes, change children, as in the following screenshot. This will change the Point light layer to PlayerShip:
Figure 4.22 – Confirm to change all children game objects

Figure 4.22 – Confirm to change all children game objects

Tip

Once you have brought something into the Hierarchy window that typically doesn't remain in the scene, don't forget to remove it once you're done. As an example, the player_ship prefab will always be instantiated by PlayerSpawner.

The end result gives us a cool, neon shiny-blue ship that doesn't affect any of the surrounding game objects, as in the following screenshot (yours may differ from this):

Figure 4.23 – Our player ship now has neon emissive lights

Figure 4.23 – Our player ship now has neon emissive lights

So, let's now move on to the particles for the player's ship.

Adding particles to our PlayerShip prefab

In this section, we will create a particle effect that will give the ship's thrusters the illusion of movement. The particle system itself is split into different component categories that will affect the behavior of how a particle acts. We will focus on placement, direction, and the life cycle of a particle effect, which is a skill that can be transferred to other effects, such as fire, smoke, water leakage, and more. The following screenshot shows our player's ship with an animated particle effect, which we are going to create now:

Figure 4.24 – Player ship with particle effect

Figure 4.24 – Player ship with particle effect

So, let's make an empty game object to hold the particle system:

  1. Right-click in an open space of the Hierarchy window.
  2. From the drop-down menu that appears, select Create Empty.
  3. Name the empty game object something such as playerJet.
  4. We want this to follow the player's ship, so drag and drop the player_ship object back into the Hierarchy window and then drag and drop playerJet onto the player_ship game object.
  5. Finally, we need to move playerJet to the rear of our player_ship object to the point where the particles start firing. I'm moving mine onto its X position by 0.5.

The following screenshot indicates where the particles will start and the playerJet transform settings:

Figure 4.25 – playerJet game object positioned behind the player ship

Figure 4.25 – playerJet game object positioned behind the player ship

That's our empty game made and in place behind the player ship model. Now, we can add our particle effect to the empty game object in the next section.

Creating a Particle Effect

In this section, we will start creating our particle effect within the empty game object from the previous section; similar to what we did a couple of sections back, we need to make all particle systems a child to the playerJet game object:

  1. In the Hierarchy window, right-click on playerJet.
  2. From the dropdown, select Effects, then Particle Effect.
  3. Rename the Particle Effect game object thruster.

We should now see a particle system that gives out its default particle spray pointing directly at us, as in the following screenshot:

Figure 4.26 – Default particle system

Figure 4.26 – Default particle system

Next, we need to scale and rotate the particle system to the correct size and make sure it's spraying in the correct direction.

With our thruster object still selected, in the Inspector window, change its Transform component settings to the following:

  • Position: X: 0, Y: 0, and Z: 0
  • Rotation: X: 0, Y: 90, and Z: 0
  • Scale: X: 0.3, Y: 0.3, and Z: 0.3

Sometimes, our Particle System object might not update, or it might disappear in the Scene window when we alter or undo its settings.

To attempt to restart Particle System to active or animating in the Scene window, select Particle System in the Hierarchy window. You will notice a Particle Effect popup at the bottom-right corner of the Scene view. Then, take the following steps:

  1. Click Stop to stop the Particle System object from emitting.
  2. Click Restart.

The following screenshot shows the Particle Effect menu found at the bottom-right corner of the Scene window:

Figure 4.27 – Particle Effect menu

Figure 4.27 – Particle Effect menu

Hopefully, if the particle system wasn't active, it is now. If it still isn't, try selecting a different game object in the Hierarchy window, then go back to the particle system and repeat the stop/restart method again.

With our thruster particle system still selected in the Hierarchy window, click the drop-down button in the Inspector window, as in the following screenshot:

Figure 4.28 – Particle System properties drop-down button

Figure 4.28 – Particle System properties drop-down button

We are now presented with a list of options in the Inspector window that might seem overwhelming, but we will only be changing a few options to give our particle system the effect we are after. Most of the Unity properties have their own ToolTips options. If you don't know what any of these are, with the Unity Editor top bar selected, hover your mouse over one of the particle system properties. After a few seconds, a description telling you about the properties will appear.

The options we need to change for our particle system are the following:

  • Duration: The length of time the particle system emits particles. If the system is looping, this indicates the length of one cycle. This option should be changed to 0.05:
Figure 4.29 – Duration property

Figure 4.29 – Duration property

  • Prewarm: When played, a pre-warmed system will be in a state as if it had emitted one loop cycle. It can only be used if the system is looping. This option should be ticked.
  • Start Lifetime: This option is in seconds. The particle will die when its lifetime reaches 0. This option should be set to 0.5.
  • Start Speed: This is the start speed of particles applied in the starting direction. This option should be set to 0.
  • 3D Start Size: This is the start size of particles.
  • Start Size should be set to 1, 2.

To get the option of more fields, do the following:

  1. Click on the down arrow to the right of the option.
  2. From the dropdown, click on Random Between Two Constants, as in the following screenshot:
Figure 4.30 – Select Random Between Two Constants

Figure 4.30 – Select Random Between Two Constants

Information

The least expensive curve is Constant as it only requires one value.

  • 3D Start Rotation: If enabled, we can control the rotation separately for each axis. This option should be ticked. To get the option of more fields, do the following:
    1. Click on the down arrow to the right of the option.
    2. From the drop-down menu, click on Random Between Two Constants and enter the following vector rotations:
  • Start Color: This is the start color of particles. The Hex Color option should be set to 00FFD5B7.
  • Simulation Speed: This scales the playback speed of the particle system. This should be set to 4.

The following screenshot provides a reference for the settings that should be set:

Figure 4.31 – Overall Particle System property values

Figure 4.31 – Overall Particle System property values

We've changed a lot of settings here. To summarize, we've created a cluster of particles that appear and soon get destroyed. If they last too long, our thruster object will travel across the screen (which you may or may not want). We have eliminated its direction because we will later change this to a force that will push the particles in a rough direction, making a less predictable pattern.

Tip

Remember that the more particles we have on the screen at once, the more demanding the scene will become. To keep things as smooth as possible, we make it so that our particles last as long as they need to (that is, they have a short lifetime) and we keep each particle size as small as possible, rather than big.

The following screenshot shows our flickering particle system as it is now:

Figure 4.32 – Current Particle System state

Figure 4.32 – Current Particle System state

Let's now continue going through the Particle System settings within the Inspector window.

Setting up the Emission section of our particle system

In this section, we will control the rate of the particles in our particle system; under each heading, I will display an information box showing the tooltip description for this section. You can view tooltips by moving your mouse over the name of the section. This also works within the Inspector window for some values. An example of a tooltip is shown in the following screenshot:

Figure 4.33 – Emission tooltip

Figure 4.33 – Emission tooltip

The next subsetting for the thruster particle system is Emission. It contains two properties (Rate over Time and Rate over Distance) but we're only going to change one of them. We will change Rate over Time (the number of particles emitted per second) to 50.

As mentioned before, if in doubt, crank the settings all the way up or down to see whether there are any instant visual answers to what the property does. You can always undo the setting. As an extra precaution, you can always save your work before changing any settings:

Figure 4.34 – Emission's Rate over Time set to 50

Figure 4.34 – Emission's Rate over Time set to 50

We're not doing anything drastic here, just lowering the number of particles a little. Later on in this chapter, it may be a good idea, for performance's sake, to lower the variable even further, depending on what platform this game is being ported to.

In the next section, we will set up how the particles enter the scene.

Setting up the Shape section of our particle system

In the next part of our setup of the particle system, we can alter the Shape setting and its properties.

Information

The Shape tooltip description is Shape of the emitter volume, which controls where particles are emitted and their initial direction.

In the Shape section, we will tighten the spawn point that the particles come from. The settings that we will change are as follows:

  • Shape: Defines the shape of the volume from which particles can be emitted and the direction of the start velocity. Set this option to Sphere.
  • Radius: The radius of the shape. Set this to 0.02.

All we need to focus on is the point that the particles have come from. Here's a screenshot of the settings that need to be set:

Figure 4.35 – Updating Shape to Sphere and its Radius to 0.02

Figure 4.35 – Updating Shape to Sphere and its Radius to 0.02

Our player's ship's thrusters display more of a concentrated glow now:

Figure 4.36 – Our player ship's glow appears more concentrated

Figure 4.36 – Our player ship's glow appears more concentrated

As already mentioned, we stopped the direction of our particle system in the very first section, and in the next section, we will use Force over Lifetime to roughly direct where the particles will go.

Setting up the Force over Lifetime section of our particle system

In this short section, we'll alter the force of where we want our particles to go. Referring back to the previous screenshot, we can see that our ship has a glow that now just needs to be pushed back slightly to give the illusion of travel.

Information

The Force over Lifetime tooltip description is Controls the force of each particle during its lifetime.

Unlike other properties, this one needs to be turned on by selecting the check box to the left of its name.

Once activated, the only setting we need to adjust is setting Z to 10, as in the following screenshot:

Figure 4.37 – Force over Lifetime value updated

Figure 4.37 – Force over Lifetime value updated

Tip

As mentioned before, be adventurous with the settings. Accidents and pushing limits can create new effects that might be useful for other parts of this game and future projects.

So, now our particle looks stretched out and resembles a thruster, as in the following screenshot:

Figure 4.38 – Particle System is now slightly stretched

Figure 4.38 – Particle System is now slightly stretched

Let's now move on to changing the texture to see whether we can add some more detail to the particles.

Setting up the Renderer section of our particle system

The Renderer section controls the visuals of each particle. This is where we can apply our own material. Within the material is a custom texture.

Information

The Renderer tooltip description is Specifies how the particles are rendered.

We are going to update the Particle System material so that it displays a sprite sheet, which we will use for animations in the next section.

Information

What's a sprite sheet? It is a series of images, typically in a grid formation, that is used for animation.

Drag and drop the thruster material file within the Project window located in the Assets/Material file path location to the Material field within the Renderer section, as in the following screenshot.

The player_ship object now has the new thruster particle system material assigned, which looks dotty. In the following screenshot, the thumbnail of the thruster material is dragged and dropped into the Material field of the Renderer part:

Figure 4.39 – Drag and drop thruster material in the Renderer/Material slot

Figure 4.39 – Drag and drop thruster material in the Renderer/Material slot

With our material and texture applied, we now have lots of dots where the glow from the rear of the ship was. We have done everything correctly, but because this texture behaves like animation, we need to update its Texture Sheet Animation settings.

Setting up the Texture Sheet Animation section of our particle system

The final step in creating this particle effect is to let Unity animate a sprite sheet correctly. Before we set this up, let's take a look at the texture we are feeding into the particle system.

Information

The Texture Sheet Animation tooltip description is Particle UV animation. This allows us to specify a texture sheet (a texture with multiple tiles/subframes) and animation or randomize over it per particle.

The following screenshot is from our thruster material:

Figure 4.40 – A sprite sheet

Figure 4.40 – A sprite sheet

The previous screenshot contains 64 images in an 8 x 8 grid. No extra settings are needed for this texture. If there were an uneven number of multiple images, then we would have to approach this differently by using Unity's sprite Editor to cut out each image individually, which can get tedious.

Further Information

More information about the sprite Editor can be found at https://docs.unity3d.com/Manual/SpriteEditor.html.

Thankfully, we don't need to worry about doing that. Let's take a closer look at the material.

In the following screenshot, we can see that the Shader option (at the top of the screenshot) is set to the Particles/Additive category (ideal shader for glow effects), which is one of the most common shaders used for a particle system.

In the Project window, under the Assets/Material file location, we have our thruster material file. Clicking on the file displays its properties in the Inspector window:

Figure 4.41 – The thruster material properties

Figure 4.41 – The thruster material properties

We can change the strength of the particle by changing its Tint Color brightness value, as in the previous screenshot. Feel free to make your own changes. I'm going to leave mine the way it is.

Coming back to the Texture Sheet Animation section, as explained, we have an 8 x 8 texture grid. This means we have to change the tiles to X: 8 and Y: 8.

Information

As you will recall, in the previous section, our particles looked dotty. That's because we were displaying all 64 images from the texture sheet in one particle. With the texture animation sheet, we have divided those 64 images into single images that will animate onto each particle.

The following screenshot shows the continuation of our particle system with the Texture Sheet Animation settings:

Figure 4.42 – Updating the Texture Sheet Animation Tiles values

Figure 4.42 – Updating the Texture Sheet Animation Tiles values

This is our end result:

Figure 4.43 – Our player ship's thruster

Figure 4.43 – Our player ship's thruster

If you're happy with the final result, we need to take one final step before saving our player_ship prefab. Because we changed the scale of player_ship in the PlayerSpawner script, we need to do the same for our thruster game object.

To change the localScale setting of the thruster game object, we need to do the following:

  1. In the Project window, navigate to Assets/Script.
  2. Double-click on the PlayerSpawner script and scroll down to the line of code that reads as follows:

    playerShip.transform.localScale = new Vector3(60,60,60);

  3. Just below the previous line of code, add the following code to size the thruster game object:

    playerShip.GetComponentInChildren<ParticleSystem>

       ().transform.localScale = new Vector3(25,25,25);

The previous code accesses the player's ship's ParticleSystem component and changes its scale to 25 on all axes.

  1. Save the PlayerSpawner script.
  2. Back in the Unity Editor, with the player_ship object selected in the Hierarchy window, click on the Overrides | Apply All button in the Inspector window.

As mentioned, be brave with the particle system; use the tooltips if you aren't familiar with them and play around with the settings—you'll soon get used to it. You could copy and paste the thruster game object and alter its color, emissions, force, scale, and more. Mix things up to create different types of thrusters.

Here's one I made earlier with seven particle systems:

Figure 4.44 – A variety of particles added to the player ship

Figure 4.44 – A variety of particles added to the player ship

Particle systems can also be manipulated via scripting, which is why as Unity programmers, we are familiar with the properties but not so much with mastering the techniques. It is also likely you will be asked, in the Unity programmer exam, about the properties of a particle system and what a particle system is good for when it comes to creating effects. Even though we didn't cover all of the properties in this section, it's good practice to have a general understanding of what each property does—for example, knowing that the Size over LifeTime property simply shrinks the particle over time.

One of the particle system properties we made use of was Texture Sheet Animation, where we provided a pre-made texture sheet to divide up our individual images to create an animation.

Information

When a particle system is made, it generates a predictable pattern. This is known as Procedural Mode; the benefit of this is that Unity knows where the particle is in the past and the future. It also helps performance when, for example, the camera is looking away from the particle system; then, it can be culled. However, if the particle system is modified by a property such as changing its simulation space to World Space, the particle system will become unpredictable and non-procedural, which will disable its ability to improve performance.

For more information about Procedural Mode, check out the following link: https://blogs.unity3d.com/2016/12/20/unitytips-particlesystem-performance-culling/.

In the next section, we will use particle systems again, but this time for the background to create stars that appear to whizz past us. We will also animate the stars at different speeds using Unity's Animator Controller.

Importing and animating the background

In this section, we are going to get familiar with Unity's Animator Controller. We will make our player's ship travel at lightspeed (well, give the impression that it is, anyway) by creating a fast-moving background of stars and particles (yes, that's right, more particles) at the start of the level, then we'll slow everything down when there are enemies up ahead.

Before we start animating at "lightspeed," we need to prepare the Hierarchy window:

  1. In the Hierarchy window, right-click on an open-space area.
  2. Select Create Empty from the dropdown.
  3. Click on the new game object and rename it GameSpeed.
  4. Do this again and name the second game object _SceneAssets.
  5. Drag GameSpeed onto the _SceneAssets game object.
  6. Make sure both game objects' Transform property values are set to Reset.
  7. Finally, drag the _SceneAssets game object from the Hierarchy window into the Assets/Prefab Project window.

    Tip

    Remember, as well as regularly saving our scene and project, we also need to make sure we make prefabs that will be situated in the scene and used on a regular basis to store the game object and its components' settings.

That's the Hierarchy window set up and ready for some extra game objects to be added to our scene. Looking at how we create an active animating scene for our game, we can tackle this with one of two approaches for a side-scrolling shooter. One way is to have a large, static background and move the player and camera through the level, tackling enemies. The other way is to keep the camera still and make the background move or animate past the camera while we trigger enemies into the scene at set times. Why would we use the second way? Because when we make a game, as a programmer, we need to focus on what is important to us—in this case, the player is most important. Also, the player is clamped within the screen ratio. Arguably, it would be more awkward for us to develop and bug-test a moving clamped camera, forcing our player across a world scene with other game objects coming into play. We can also consider physics as a factor with debris and even more game objects colliding with each other, which can cause potential issues. As a programmer, I find it is always best to look for the simplest option.

With that said, let's move on to making our background:

  1. Right-click on GameSpeed in the Hierarchy window.
  2. Select Create Empty from the dropdown.
  3. Click on the new game object and rename it ScreenBackground.

The ScreenBackground game object is going to house the stars particle system. The particle system that we will bring into our scene is pre-made; I didn't think it would be necessary to continue making more particles as we have already made one for our player's ship.

From the Assets/Particle Project window, drag the warpStars_pe prefab onto the GameSpeed game object in the Hierarchy window to make it a child.

With the changes we have made in this section, the Hierarchy window content should resemble the following screenshot:

Figure 4.45 – Current Hierarchy layout

Figure 4.45 – Current Hierarchy layout

We have updated our Hierarchy window again with the second particle system for this chapter. This has improved the structure and increased clarity as our game starts branching out into more functionality. Let's now continue focusing on the particle system with its placement in the world scene:

  1. In the Hierarchy window, select warpStars_pe if it isn't selected already.
  2. Moving our attention over to the Inspector window, set its Transform settings to the following:

With our particle system set up in the correct place, we can now focus on adding another layer to the background of our game, which will be a ScreenBackground texture on a large quad polygon.

Let's continue adding more functionality to the ScreenBackground game object:

  1. In the Hierarchy window, select ScreenBackground.
  2. In the Inspector window, click on the Add Component button.
  3. From the dropdown that appears, start typing Mesh Filter until it is available to click on from the list.

The following screenshot shows the Inspector window for ScreenBackground, equipped with a three-dimensional Quad polygon mesh:

Figure 4.46 – Quad mesh filter selected from the Mesh dropdown

Figure 4.46 – Quad mesh filter selected from the Mesh dropdown

With the Quad mesh created, we need to make it visible in our Scene and Game windows with the Mesh Renderer component.

  1. Select the ScreenBackground game object in the Hierarchy window and in the Inspector window, click on the Add Component button.
  2. In the dropdown, start typing Mesh Renderer until you see it in the list, then click on it.

Similar to what we did for our player_ship prefab and our previous particle system, we need to create and apply a material to our ScreenBackground object:

  1. Right-click in the open space of the Project window in the Assets/Material file location.
  2. Click on Create from the dropdown.
  3. Then, click on Material.
  4. With the new material selected, rename it backGround_Wallpaper.

Because our ScreenBackground game object now has a MeshRenderer object and we have created a material for it, we now need to apply it:

  1. In the Hierarchy window, select ScreenBackground.
  2. Drag and drop the backGround_Wallpaper material from the Project window to the Mesh Renderer section, into the Element 0 slot of the Materials subsection, as in the following screenshot:
Figure 4.47 – Drag and drop the backGround_wallpaper material into Element 0

Figure 4.47 – Drag and drop the backGround_wallpaper material into Element 0

Let's rewind and confirm what we have done so far in this section. We have our game objects in their correct positions in the Hierarchy window and we have our second particle system set up, positioned, rotated, and scaled. We've just created our material, named it, and placed it into backGround_Wallpaper.

Now, we'll set the material up to be something quite basic. It doesn't require a lot of fancy shaders, so just a simple low-resource mobile shader will be fine.

Information

Shaders are typically mathematical scripts that tell our material how its graphics and light behave.

Make sure ScreenBackground is still selected in the Hierarchy window.

In the Inspector window, scroll down to the Material component:

  1. If the Material component isn't expanded, click on the arrow next to the white sphere.
  2. With the Material component expanded, we can see a lot of maps that we won't need, so let's change the shader to a more basic one.
  3. Click on the selection dropdown from the Shader field. Typically, Standard will be the default shader.
  4. From the dropdown, click on Mobile.
  5. Then, click on Diffuse.

The following screenshot shows this procedure:

Figure 4.48 – Selecting a Mobile Diffuse shader for our material

Figure 4.48 – Selecting a Mobile Diffuse shader for our material

This has chopped our Material properties down to the minimum requirement, as in the following screenshot:

Figure 4.49 – backGround_wallpaper material's current state

Figure 4.49 – backGround_wallpaper material's current state

The two things we really care about in this Material component are the Texture we are going to supply to it and its Offset value.

Information

What's an offset? Offset is the position where our texture is applied on our UV map. For example, if we increase the Offset property's X position, the texture applied to the material will overlap and appear on the other side of our quad.

We will now continue working with our background Material component by adding our ScreenBackground texture:

  1. With the Material component still in the Inspector window, there is a large square at the top right called None (Texture). Click on Select (use the previous screenshot as a reference).
  2. A dropdown appears. Start typing spaceBackground until the option comes up, then click on it.

We should have a quad named ScreenBackground that is black with white dots on it, as in the following screenshot:

Figure 4.50 – Our quad spaceBackground

Figure 4.50 – Our quad spaceBackground

Before we start animating this texture, we need to do the same as what we did for our particle system and update its Transform properties: Position, Rotation, and Scale. We need ScreenBackground to cover the camera's frustum angle and our image to show up after the Transform update.

  1. In the Hierarchy window, select the ScreenBackground game object.
  2. In the Inspector window, update its Transform component with the following settings:

The following screenshot shows our current scene view:

  • We have a very large quad with a space texture.
  • We have a white grid-like camera view.
  • Our player's ship is in between the camera and the quad.
  • The bottom right shows us what the user sees as an end result:
Figure 4.51 – Our current game scene environment setup

Figure 4.51 – Our current game scene environment setup

We have updated our Hierarchy window to hold two background layers. The first layer shows passing stars with the second particle system we added from this chapter's downloads file. The second is a game object that holds a quad polygon with a texture. Let's now move on to creating the Animator Controller for our background and space warp particle.

Adding an Animator Controller

Using the Animator Controller is a way of controlling animation states. We will have our player's ship traveling at lightspeed for a couple of seconds, then we'll slow things down just before the enemies come to attack our player.

The left-hand-side depiction of our ship in the following screenshot shows more streaking particles than the ship on the right. The starry background also moves faster on the left than on the right (which you can't really see in these still screenshots):

Figure 4.52 – Animating the stars in the background will follow next

Figure 4.52 – Animating the stars in the background will follow next

So, let's create and attach the animator to the parent of the ScreenBackground object and the particle system.

Tip

With the Animator Controller, if you are animating multiple game objects at once, make sure your Animator Controller is the parent to these game objects. You can't have a child animating its parent (parent refers to the game objects above the object in the Hierarchy window).

Looking at the Hierarchy window, we have made all the background effects in this chapter within the GameSpeed game object. As mentioned in the information box, the Animator Controller animates all the children, but it can't animate parents. With that said, let's add the Animator Controller:

  1. In the Hierarchy window, select the GameSpeed game object.
  2. In the Inspector window, click on the Add Component button.
  3. In the dropdown, start typing Animator until it appears and then click on it.

The following screenshot shows the Animator component (which houses the Animator Controller) selected for the GameSpeed game object:

Figure 4.53 – Select the Animator from the dropdown

Figure 4.53 – Select the Animator from the dropdown

We now have the Animator component attached to our GameSpeed game object. The next thing to do is create and attach the Animator Controller to the Controller field. The following screenshot shows the Animator component settings:

Figure 4.54 – The Animator Controller component

Figure 4.54 – The Animator Controller component

Before we do that, we need to create an Animator folder. In the Project window, navigate to the Assets folder and create an empty folder. Name it Animator.

Go inside the Animator folder and continue making the Animator Controller:

  1. Right-click in the Project window open space.
  2. Click on Create.
  3. Click on the Animator Controller (see the left side of the following screenshot for reference).
  4. Rename the new Animator Controller GameSpeed_Controller.
  5. Finally, drag and drop this Animator Controller to the GameSpeed Animator Controller in its Inspector window (refer to the right-hand side of the following screenshot for reference).

The following screenshot shows the creation of an Animator Controller and how to apply it to the Animator component:

Figure 4.55 – Drag and drop the GameSpeed_Controller into the Animator Controller slot

Figure 4.55 – Drag and drop the GameSpeed_Controller into the Animator Controller slot

In this section, we created and applied our Animator component and Animator Controller to our GameSpeed game object. In the next section, we will look at animation states within the Animator Controller.

Creating states in the Animator Controller

In this section, we will use the Animator Controller to create a state for animating the background scene and particles at high speed; followed by the second state, which will slow the background and particles down to represent the player's ship going at a slower speed (which also helps make our game less distracting). Let's make the first state.

To create a state, follow these instructions:

  1. Double-click on the GameSpeed_Controller object that we placed in the GameSpeed Animator component.
  2. The Animator window will open with some default states: Entry, Any State, and Exit.
  3. Right-click in an open space within the Animator window.
  4. A dropdown will appear. Click on Create State.
  5. Then, click on Empty:
Figure 4.56 – Create an empty animation state

Figure 4.56 – Create an empty animation state

As you can guess, we've just created an empty state.

  1. Repeat this process to create a second state.

    Further Information

    Unity's Animator Controller also offers layering with our animation. So, for example, we can animate a player who can run, jump, and shoot. It's likely that we will want a couple of these animations playing at the same time, and we can do so with Layers (see the top-left corner of the previous screenshot). We can change the influence over each animation, or Weight, as it's referred to in Unity, and we can use the Override (information from other layers will be ignored) or Additive (added on top of another animation) settings to blend between animations.

    If you would like to find out more about animation layers, go to https://docs.unity3d.com/Manual/AnimationLayers.html.

Once we have created our second state, let's do a bit of housekeeping:

  1. Click and drag Exit and Any State out of the way. We won't be using these. Entry will automatically attach itself to the first state we make.

Let's now rename our states.

  1. Click on the orange state called New State.
  2. In the Inspector window, click in the top-right corner where it says New State.
  3. Delete this and rename it BackGround_Intro_Speed.
  4. Press Enter on your keyboard to make sure it saves the name. If you click away, it sometimes doesn't save the change.
  5. Now, rename the other state we made, currently titled New State 0. Rename this second state to BackGround_InGame_Speed.

    Tip

    You can zoom in and out and pan around the Animator window with your mouse wheel.

    To zoom in, scroll the wheel up.

    To zoom out, scroll the wheel down.

    To pan, hold the middle mouse button down.

Don't worry about the exact placement of the states; that's more of a cosmetic issue. We just need to have an Entry state connecting to a BackGround_Intro_Speed state, with a BackGround_InGame_Speed state near to it.

The following screenshot shows the three states we should be focusing on:

Figure 4.57 – Animator Controller states

Figure 4.57 – Animator Controller states

These three animation states will eventually have lines attached to each of them; these lines allow a condition to be made (such as an if statement; see https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/if-else for more information) so that one state can move to another.

Before we look at this, we also need to be aware that each state can run at different speeds. We will alter the speed of the states to go in line with the speed of the animations they house. To change the animation speeds of our state, do the following:

  1. In the Animator window, click on the BackGround_InGame_Speed state.
  2. In its Inspector window, change its Speed value from 1 to 0.1.

The other state will remain the same.

As the scene starts, the first state is BackGround_Intro_Speed, then once that animation is connected to it (which we currently haven't done yet), BackGround_InGame_Speed is played next. We need to connect the last state so that it can be played after.

To connect a state, do the following:

  1. In the Animator window, right-click on the BackGround_Intro_Speed state.
  2. From the dropdown, click on Make Transition.
  3. Then, click on BackGround_InGame_Speed.

We should now have one state connected to another.

In this section, we delved deeper into the Animator Controller, creating our intro and in-game animation states. We set the speed of the state and, finally, connected up the transition lines so that we know the flow of our animation states. All this structuring of extra game objects, the Animator Controller, and the states means we are now at the stage where we can start animating our scenery.

Animation

Finally, we are actually going to animate something. We will only cover a basic animation but it will give us an understanding of the animation setup, which will support us in the exam and future projects.

So, let's just jump in and animate the background and our background particles:

  1. In the Project window, go to the Assets/Animator folder location.
  2. Right-click in the open space and click on Create from the dropdown.
  3. Then, click on Animation.
  4. Name the new animation BackGround_InGame_Speed.
  5. Repeat the process and name the new animation BackGround_Intro_Speed.

The following screenshot shows the creation of an Animation file:

Figure 4.58 – Creating an Animation file in the Unity editor

Figure 4.58 – Creating an Animation file in the Unity Editor

The introduction animation will be played once because it will be a surge of stars, then the second animation will loop, playing continuously to give the illusion of never-ending stars and particle stars moving past the Game window.

With that said, in the Project window, click on the BackGround_InGame_Speed animation file, and in the Inspector window, check the box next to Loop Time.

We now need to apply our two Animation files to their animation states in the Animator window.

To hook these new Animation files up, do the following:

  1. In the Hierarchy window, select the GameSpeed game object.
  2. Double-click on GameSpeed_Controller.
  3. The Animator window opens up. Select one of the two animation states we created in the Animator Controller.
  4. Drag and drop the Animation file we just made to the Motion field of the Inspector tab (refer to the following screenshot).
  5. Select the other state that we created and repeat the drag-and-drop process with the other matching Animation file.

We now have the two Animator Controller states with an empty animation clip applied.

The following screenshot shows our BackGround_Intro_Speed animation file dragged and dropped into the Animation State | Motion field:

Figure 4.59 – Drag and drop the BackGround_Intro_Speed file into the Motion slot

Figure 4.59 – Drag and drop the BackGround_Intro_Speed file into the Motion slot

Further Information

You can also create a blend tree in the Animator Controller. A blend tree is specifically built to blend a series of animations as one form. Within the blend tree, there are different types: 1D, a series of 2D, and Direct.

Blend trees can be useful to change an animation from walking to running (1D) or for more complex animations, such as facial expressions (Direct).

To learn more about blend trees, check out https://docs.unity3d.com/Manual/class-BlendTree.html.

Let's stay focused on our Animation file and start animating the scene.

First, we need to open the Animation window:

  1. At the top of the Unity Editor window, click on Window.
  2. Then, click on Animation, or you can use the Ctrl (or command on macOS) + 6 shortcut.
  3. Next, back in our Project window, we need to click on the BackGround_Intro_Speed animation file (this should be located in the Assets/ Animator folder structure). This will update the Animation name within the window (use the following screenshot as a reference):
Figure 4.60 – Animation window with the BackGround_Intro_Speed animation selected

Figure 4.60 – Animation window with the BackGround_Intro_Speed animation selected

Tip

Like most windows within Unity, we can lock the window so that it doesn't update to another game object or, in this case, animation.

To lock the window, click on the padlock symbol in the top-right corner of the Animation window.

Locking the animation is probably a good idea, at this point, as we will be clicking on different game objects within the Hierarchy and Inspector windows.

We will animate the spaceBackground texture first:

  1. Keep the GameSpeed game object selected in the Hierarchy. If we select something else, we will lose the animation functionality in the Animation window.
  2. In the Animation window, click on the round red record button (above the Animation filename). Notice how the Animation window turns partially red, telling us we are in record mode.
  3. Then, in the Hierarchy window, click on ScreenBackground.
  4. Now, in the Inspector window, we need to focus on changing backGround_Wallpaper material settings.
  5. Also, make sure our Animation white indicator line is all the way to the left, as in the following screenshot.
  6. Next, change the X value of Offset from 0 to -10. Notice how the fields turn red as this is noted in the Animation window.
  7. Now, click and hold the white line in the Animation window and move it across to the right so that it isn't sitting on top of the animation it has just made:
Figure 4.61 – Animating the Offset value of the backGround_wallpaper material properties

Figure 4.61 – Animating the Offset value of the backGround_wallpaper material properties

  1. Change the X value of Offset, this time from -10 to 1. Notice, in the following screenshot, how the white lines in the Animation window have moved to roughly 300 (5 minutes):
Figure 4.62 – Adding a second keyframe and changing the backGround_wallpaper Offset value

Figure 4.62 – Adding a second keyframe and changing the backGround_wallpaper Offset value

  1. Try moving the white lines backward and forward (scrub is the term used for this by animators) between our two animation points. Notice how the stars on the quad are moving.

Let's now do something similar with the warpStars_pe particle system:

  1. Check that the Animation window is still locked and recording.
  2. Move the animation indicator line all the way back to the left to the start of the other animation keyframe.
  3. From the Hierarchy window, select warpStars_pe.

In the Transform section of the Inspector tab, make the following changes:

Then, scrub (move) the white lines to the exact same spot as the starry background keyframe.

Tip

We can click the Next Frame button in the Animation window to jump to the next keyframe (the button to the right of the Play button, not the Editor play button).

With the Animation window still in recording and the warpStars_pe game object still selected, update its Transform settings in the Inspector window with the following values:

  1. Try scrubbing backward and forward in the Animation window to see how it looks in the Scene view. You should see the particles moving from right to left.
  2. In the Animation window, turn off the record setting.

That's one animation down and one to go. The next process is similar to what we've already done but a little quicker.

With the warpStarts_pe still selected in the Hierarchy window, and with the Animation window still open, do the following:

  1. Click and drag to select all keyframes with your mouse, as in the following screenshot:
Figure 4.63 – Select all keyframes

Figure 4.63 – Select all keyframes

  1. Let go of the mouse and press Ctrl (or Command on macOS) + C to copy the keyframes.
  2. Let's now switch over to the BackGround_InGame_Speed animation by clicking on the name of our current animation and selecting the other, as in the following screenshot:
Figure 4.64 – Selecting our second animation file, BackGround_InGame_Speed, in the 
Animation window

Figure 4.64 – Selecting our second animation file, BackGround_InGame_Speed, in the Animation window

  1. Notice how the name has changed to reflect the animation we are in.
  2. Now, click in the graph area and use the Ctrl (or command on macOS) + V keyboard commands.
  3. We should now have pasted the previous animation into this one. We can manipulate the results within the window, as in the following screenshot:

    Tip

    If you can't see all keyframes in the Animation window, select an open area within the window and press F on the keyboard. This will auto-fit all keyframes in.

Figure 4.65 – BackGround_InGame_Speed animation file with its pasted keyframes 
in the Animation window

Figure 4.65 – BackGround_InGame_Speed animation file with its pasted keyframes in the Animation window

Finally, we can manipulate the keyframes:

  1. Click on the Animation window to start recording.
  2. From the Hierarchy window, select ScreenBackground.
  3. From the Inspector window, change the backGround_Wallpaper Offset setting X from -10 to 1.
  4. Click on the Next Frame button (the button to the right of Play in the Animation window) to go to the last frame and change the X value of Offset from 1 to 2.
  5. Next, we alter the warpStars_pe animation within the Animation window. Click on the first warpStars_pe keyframe at the far left and press Delete on the keyboard. Now, move the last keyframe from the end to the beginning.

Before we stop recording, we need to stop the animation from easing out (slowing down near the end of the animation).

To make it so that our backGround_Wallpaper setting is on a fixed animation speed, we need to do the following:

  1. In the Animation window, click and drag to select all the keys.
  2. Right-click, and from the dropdown, select Both Tangents | Linear.
  3. Stop recording.

Let's recap what we have done so far. We have taken the X value of Offset from the last animation and pasted it to the start of this animation. Then, we incremented the X value of Offset by 1 so that it comes back to the start of its X value of Offset.

We moved the particles from left to right in the first animation; we kept the particles on the right in the second animation to stop the scene from being too cluttered and to show that we aren't going as fast.

We are now at the final steps of the animation; the rest of the work is done within the Animator Controller. From the Animator Controller, we can state what needs looping and how our animations relate to each other.

For the last time in this chapter, let's visit the animation controller and start splicing our states from one to another:

  1. From the Hierarchy window, select the GameSpeed game object.
  2. Then, in the Inspector Animator component, double-click on GameSpeed_Controller.
  3. Now, click on the transition line between BackGround_Intro_Speed and BackGround_InGame_Speed (circled in the following reference screenshot).

With regard to the transition between one animation and another, the following screenshot sets the example of these states via the two blue bars. Select the following settings:

  • Has Exit Time: Checked.

The Has Exit Time tooltip reads Transition has a fixed exit time.

  • Exit Time: 0.1

The Exit Time tooltip reads Exit time is the normalized time from the current state.

  • Fixed Duration: Checked.

The Fixed Duration tooltip reads Transition duration is independent of state length.

  • Transition Duration (s): 2.5

The Transition Duration (s) tooltip reads Transition duration in seconds.

  • Transition Offset: 0.1

The Transition Offset tooltip reads Normalized start time in the next state.

  • Interruption Source: None

The Interruption Source tooltip reads Can be interrupted by transitions from:

Figure 4.66 – Transition values updated in the Inspector window

Figure 4.66 – Transition values updated in the Inspector window

The figures are rough for this transition. It's also quite unnatural to enter perfect figures for an animation. I recommend removing any enemies from the scene. Click the Play button and alter the selection bar above the graph. Each time this selection changes, the animation will play again. Keep an eye on the Animator Controller; you will see a progress bar start and end. This will help the timings of when the animation will splice over.

Information

Animation transitions can help blend one animation into another. For example, if we want an animation to move into another in an exact time frame, we would focus on the Fixed Duration and Transition Duration parameters (shown in the previous screenshot).

For more information on animation transitions, check out https://docs.unity3d.com/Manual/class-Transition.html.

The results I have are very smooth and work well, but I recommend forgetting the figures. Put the Editor in Play mode and drag the selection bar back and forth until you get the splice that is right for you.

That is the end of the Animator Controller settings. It's one of those things that takes a long time to explain but is very quick to do once you know how.

You might be eager to get back to coding as we have mainly been working in Unity's Editor tools. So, let's return to the IDE and start looking at animating next.

Animating our three-dimensional enemies

Here's a really easy, quick animation with the script for your enemies. Currently, the enemies just move up and down in a wave pattern. However, the units themselves remain static.

Let's give our enemies a bit of extra life with some code:

  1. In the Project window, go to Assets/Prefab/Enemies.
  2. Double-click on the enemy_wave prefab and select the enemy_wave_ring in the Hierarchy window.
  3. In the Inspector window, click on the Add Component button.
  4. Click on New Script at the bottom of the dropdown.
  5. Name the new C# script BasicEnemyRotate.
  6. Then, enter this code:

    using UnityEngine;

    public class BasicEnemyRotate : MonoBehaviour

    {

    [SerializeField]

    float speed = 0;

    void Update ()

      {

       transform.Rotate(Vector3.left*Time.deltaTime*speed);

      }

    }

This is a tiny script that animates the part of our enemy. There are two things to look closely at:

  • The variable is a private float named speed with a SerializeField attribute so that it can be seen in the Inspector window. More about this attribute can be found at https://docs.unity3d.com/ScriptReference/SerializeField.html.
  • In our Update function, we are rotating the game object over time based on the speed we are setting it at. I have set my enemy rotation speed to 200 in the Inspector

Once you have created, added and updated your script via the Inspector window, we need to save enemy_wave prefab new content.

  1. To update the prefab click the left arrow in the top left corner of the Hierarchy window, as shown in the following image:

Figure 4.67: Updating prefab content

  1. A pop up window will appear to confirm the new changes, simply click Save.
  2. Now that you know how to update the prefab, select the enemy_wave prefab from the Project window again, double click it as before.

Next we are going to update it's visuals by following these steps:

  1. Expand the enemy_wave game object in the Hierarchy window and select enemy_wave_core.
  2. Select the small, round remote button to the right of the Element 0 parameter in the Mesh Renderer component under the Inspector window.
  3. Select the basicEnemyShip_Inner material.
  4. Select enemy_wave_ring from the Hierarchy window.
  5. From the Inspector window, click on the small, round remote button in the Mesh Renderer component, and from the dropdown, select basicEnemyShip_Outer.
  6. Finally, update the prefab as we did before by clicking the arrow in the top left corner of the Hierarchy window and then clicking Save on the popup window..
  7. Click Play at the top of the Editor and we should now see our enemies rotating and in color:
Figure 4.67 – Rotating enemies moving toward the player

Figure 4.67 – Rotating enemies moving toward the player

Lastly, move all new scripts into the Script folder.

Later on, we could speed up the enemies' rotation, depending on the player's skill level, to make them look more aggressive.

This was a long chapter, but we covered particles and animation, which are important to know for the exam. With more practice and understanding, the benefits of what we've learned will really start to show. Now is a good time to get used to these two skills as they are commonly overlooked. It's these skills that will make you stand out from the rest.

Summary

In this chapter, we jumped into the art world. We brought our player's ship to life, giving it a series of maps and a light. Then, we moved on to Unity's particle system and created a thruster object with an option to expand it. Then, we moved into animation and got our hands dirty, adding and animating the scene background and animating particle warp stars. We covered states and transitions, then calmed things down with some animation code for our enemies.

That was a lot! If you ever revisit this chapter, you will go through it much quicker as you'll see, if you haven't already, that you can copy and paste animation keyframes, copy and paste particle systems, and tweak them.

In the next chapter, we will look at a new scene where we upgrade the player's ship with the introduction of a shop before a level starts. We will also introduce the popular concept of free-to-play games, which is typically found in mobile games where the game is free to download, and the user is given the option of earning in-game credits by watching an advert.

Well done! What you have learned will all contribute to your exam and future projects.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset