In this section, we will learn how to add our penguin player to the game and how we can make her alive by writing scripts, applying physics, and adding colliders in it.
Adding the penguin
Importing the penguin Sprite
Before we do anything, we need a player Sprite or image. For our Perky Penguin game, we have designed a penguin sprite. The following figure shows the penguin that is included as the player sprite of the game:
To import an image in to Unity, right-click on the Graphics folder in the Project Browser panel and click on Import New Asset..., as shown in the following screenshot:
These assets can be anything that is supported by Unity, such as images, audio files, 3D models, textures, materials, and scripts.
Unity shows all the images with nice previews. It must be noted here that if Unity is in 2D mode, then unity will show images as sprites and if mode is set to 3D mode it shows the images as textures. Figure 1.36 shows both scenarios. The following screenshot shows the image imported as sprite and the screenshot besides it shows image imported as texture:
If the penguin image is imported as texture, then there is nothing to worry about. Select the image from Project Browser panel, and in the inspector change the Texture Type to Sprite and click Apply. It is shown in the following figure:
Creating penguin game object
After the assets are imported, which in our case is a single penguin image, we have to create a game object of player. Usually game objects are created by right-clicking in Hierarchy and selecting Create Empty as shows in the following figure:
But, in order to create sprites as game objects, simply drag sprites from the Project Browser panel to Hierarchy or Scene View panels and a game object will be created with the name of image file which is penguin_fly.png here. This is shown in the following figure:
Now it's time to configure the penguin_fly game object of Hierarchy to get used in the game. Now select the penguin_fly object and make following changes in the Inspector panel.
- Change the game object's name to penguin.
- Set the position values to (0, 0, 0).
- To add a collider in the penguin, click Add Component in the inspector and select Circle Collider 2D from Physics2D menu as shown in the following figure. More about Colliders can be read here https://docs.unity3d.com/ScriptReference/Collider.html:
- Set the value of Radius of Circle Collider 2D to 0.6.
- To make the penguin behave as a physical object, we have to add Rigid Body component. To add it, click Add Component in the Inspector panel and select Rigid Body 2D from Physics2D as shown in the following figure:
- Set Fixed Angle checkbox state as checked on to avoid penguin to be rotated while falling or jumping due to physics dynamics.
The following figure below shows all the steps performed on the penguin game object:
Starting from position, we have set the position to zero just for testing purposes. We will change it later when we put penguin at its initial position. The Sprite Renderer component is already added in the penguin game object because penguin game object was created from sprite by dragging it from Project Browser panel. The Sprite Renderer allows any game object to show an image on the screen from any sprite. In order to make any game object to react to physics collisions and get collided with each other, game object requires collider component in it. We have added Circle Collider 2D on the penguin object. You can choose any type of collider from the list. But it is recommended to choose the collider which is very light and fills the whole colliding area. The following figure shows the penguin with different colliders applied to it:
Using complex colliders like Polygon Collider 2D makes it harder to detect collision for the physics engine to detect collision, which in turn, creates a performance penalty. Finally, in order to apply gravity on the penguin, we have added Rigid Body 2D component. Rigid Body 2D allows any game objects to behave to the gravity, friction, physics kinematics and so on. We have check Fixed Angle to on state of the Rigid Body 2D. If this is set to off, then penguin will also rotate due to wind, friction, gravity, or any other force applied on it. So in order to avoid her to rotate while jumping, we have set Fixed Angle as checked.
When you run the project, you will notice that penguin will fall down on the screen. It is because of the gravity is pulling penguin downwards and it goes off the screen. The Gravity Scale value, which is 1 by default, decides the gravity of the penguin. If we remove or disable Rigid Body 2D component, then penguin will never move. So, it must be noted that without rigid body no force and collision will be applied on the game object.
Adding script behavior on penguin object
After setting physics components and position on penguin object, it's time to define some logic behavior of the penguin. The game's requirements are to let penguin fly through its jetpack when screen is touched by player and penguin will fall when touch is stopped. These kinds of logic are defined in Unity through scripts. Unity supports 2 kinds of scripts; C# and JavaScript. You can use any of these scripts. Even you can also use few files in C# and few other files in JavaScript in the same project. Throughout this book, we will do all the scripting through C#.
- We will start by creating a C# script file in Scripts folder in Assets by right-clicking on Scripts folder and choose C# Script from Create menu as shown in the following figure:
- Let's call this script as PenguinController.cs and when you open it, the Unity's default Code Editor Visual Studio will start and open the newly created script file it as shown in the following figure.
- You might notice some code already written in this file. We will discuss about it in a while. Now a script has been created, but this script is not linked or connected to our penguin object or even the game. In order to apply it on the penguin object, select penguin game object, click on Add Component in the Inspector panel, and choose PenguinController.cs from Scripts menu as shown in the following figure:
Now, as the script is applied on the penguin game object, let's write some logic and code to make the penguin fly. Open PenguinController.cs file from project browser panel by double-clicking it in MonoDevelop. The code which is already written looks like the following screenshot:
- The PenguinController class is inherited from MonoBehaviour class. Any script to be applied on any game object placed in the scene should be a MonoBehaviour class and this is done by inheriting the class from it. MonoBehaviour class provides some basic functionality for game objects such as its life cycle like when object is created, when it is active, when it is destroyed etc. Also it provides some functionality like interactions such as mouse down or mouse up etc. For now, we have only two methods Start() and Update(). The Start() method is called when the game object becomes first time active on the scene at runtime and Update() method is called on each frame if the game object is enabled or active.
- Now, let's start our logic for penguin. We will start from creating a variable jetpackForce in the class like this:
public float jetpackForce = 75.0f;
- We have set its initial float value to 75 and f letter is to make it float literal. There is an interesting thing about Unity that all the public fields in any class will be shown in game object's inspector component and can be altered or modified directly from the editor without opening the code file. The following shows the jetpackForce variable's field in the inspector panel:
- Next is to use this jetpackForce's value as the force to apply on penguin when touch is pressed. In order to detect touches, we have to use Input.GetButton() method. But this method is better used in either Update() or FixedUpdate() methods of MonoBehaviour class. The FixedUpdate() method is called every fixed frame instead of every frame. Meaning that in FixedUpdate() if the FPS of the game is 60 then the FixedUpdate function will be called 60 times in a second. Irrespective if there are any changes to the scene. In comparison the Regular Update () function gets doesn't stick to the 60 fps rule and will update when there is a change in the scene. This should be used when dealing with RigidBody. As our penguin is a RigidBody2D, so it's better to use FixedUpdate() method than Update(). The PenguinController.cs script doesn't contain FixedUpdate() method, so let's add the following code in the class now:
void FixedUpdate()
{
bool jetpackkActive = Input.GetButton ("Fire1);
if (jetpackActive = true) {
this.GetComponent<Rigidbody>().AddForce(new Vector2(0,
jetpackForce));
}
}
- There is nothing difficult here. We are polling for the input of Fire1 button which is a left-click in case of any PC, Linux, or MAC build and it changes to touch on Android, iPhone or other touch device. If the screen is touched, then GetButton() will return true value, which in turn lets script add force by calling AddForce() method of the RigidBody2D component and passing the jetpackForce value in the y-direction.
Following is the whole PenguinController.cs file's code:
- Now, when you run the game the penguin will start falling. On clicking on screen, the penguin will rise up a little and will start falling again. The more frequently clicks are performed, the higher penguin will go up and it will easily be out of the screen within 2 or 3 clicks. Also it is falling very fast. In order to adjust its speed, either we decrease Gravity Scale from RigidBody2D of the penguin object as shown in the following figure on left side or we decrease the Gravity in the Physics2D settings shown in the figure on right side.
We will change the Gravity value of Physics2D settings to -15. You can open Physics2D settings from Edit - Project Settings - Physics2D menu.
Now run the game, and you will notice the penguin will fall slower than before. On clicking many times, you might notice that penguin gets out of the screen. This kind of behavior in the games should be avoided. So, in order to limit the penguin within the screen bounds, we will add floor and ceiling in the game. Let's see how it's done in the next section.
Limiting the penguin between screen bounds
Adding floor and ceiling is quite simpler job. We will create an empty object first. It should be noted that we are not importing any images or sprite assets in the scene, because we only need boundaries not the visuals of those about how these will look. Here is how we create our floor object.
- Create empty game object by choosing GameObject - Create Empty menu.
- Select newly created empty game object in the Hierarchy panel.
- Rename it to floor.
- Set its Position to (0, -3.25, 0).
- Set its Scale to (14.4, 1, 1).
- Add Box Collider 2D component by clicking on Add Component, and selecting Physics2D - Box Collider 2D option.
Now you should be seeing a green rectangle on bottom of screen. This is the box collider of the floor and when you run the game, the penguin will never fall off the screen and it will stop when collided with the floor.
Similarly, now add ceiling game object with the name ceiling and its position of (0, 3.25, 0) and its scale of (14.4, 1, 1). Apply Rigid Body 2D component on the ceiling object, and now run the project. You will observe that penguin now never leaves the screen and it is limited between the upper and lower parts of the screen.