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:
So, let's jump in and make a start on changing the appearance of the player's ship.
We will look at programming core interactions:
We will also look at working in the art pipeline:
We will cover the programming for scene and environment design:
Finally, we will cover working in professional software development teams:
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.
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:
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:
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.
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:
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:
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:
The following screenshot shows the location of the Mesh Renderer component situated within 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.
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:
Now, we will apply these maps to the PlayerShip model by taking the following steps:
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:
Another way of fixing this issue with the normal map is by doing the following:
The following screenshot shows a normal map file selected from the Texture Type dropdown and the Normal map selection in the dropdown:
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:
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:
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.
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:
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:
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:
With the Point light selected from the Hierarchy window, we can alter our new light settings in the Inspector window:
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.
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:
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:
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.
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):
So, let's now move on to the particles for the player's ship.
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:
So, let's make an empty game object to hold the particle system:
The following screenshot indicates where the particles will start and the playerJet transform settings:
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.
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:
We should now see a particle system that gives out its default particle spray pointing directly at us, as in the following screenshot:
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:
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:
The following screenshot shows the Particle Effect menu found at the bottom-right corner of the Scene window:
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:
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:
To get the option of more fields, do the following:
Information
The least expensive curve is Constant as it only requires one value.
The following screenshot provides a reference for the settings that should be set:
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:
Let's now continue going through the Particle System settings within the Inspector window.
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:
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:
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.
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:
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:
Our player's ship's thrusters display more of a concentrated glow now:
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.
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:
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:
Let's now move on to changing the texture to see whether we can add some more detail to the particles.
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:
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.
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:
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:
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:
This is our end result:
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:
playerShip.transform.localScale = new Vector3(60,60,60);
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.
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:
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.
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:
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:
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:
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:
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:
The following screenshot shows the Inspector window for ScreenBackground, equipped with a three-dimensional Quad polygon mesh:
With the Quad mesh created, we need to make it visible in our Scene and Game windows with the Mesh Renderer component.
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:
Because our ScreenBackground game object now has a MeshRenderer object and we have created a material for it, we now need to apply it:
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:
The following screenshot shows this procedure:
This has chopped our Material properties down to the minimum requirement, as in the following screenshot:
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:
We should have a quad named ScreenBackground that is black with white dots on it, as in the following screenshot:
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.
The following screenshot shows our current scene view:
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.
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):
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:
The following screenshot shows the Animator component (which houses the Animator Controller) selected for the GameSpeed game object:
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:
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:
The following screenshot shows the creation of an Animator Controller and how to apply it to the Animator component:
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.
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:
As you can guess, we've just created an empty 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:
Let's now rename our states.
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:
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:
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:
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.
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:
The following screenshot shows the creation of an Animation file:
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:
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:
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:
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:
Let's now do something similar with the warpStars_pe particle system:
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:
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:
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.
Finally, we can manipulate the keyframes:
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:
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:
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:
The Has Exit Time tooltip reads Transition has a fixed exit time.
The Exit Time tooltip reads Exit time is the normalized time from the current state.
The Fixed Duration tooltip reads Transition duration is independent of state length.
The Transition Duration (s) tooltip reads Transition duration in seconds.
The Transition Offset tooltip reads Normalized start time in the next state.
The Interruption Source tooltip reads Can be interrupted by transitions from:
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.
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:
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:
Once you have created, added and updated your script via the Inspector window, we need to save enemy_wave prefab new content.
Next we are going to update it's visuals by following these steps:
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.
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.