Even in today's world, people remember Mario, Sonic, and Mega Man. Of course, Mario was first introduced in the eighties, followed by Mega Man and Sonic, but even now the new generation loves these games. Yes, we are talking about the old style 2D platform games, which are still quite popular today, especially among indie game developers.
In this book, we will start the first project with a 2D platform game because there are some basic tricks for a 2D platform game that will help youâthose who haven't got into the 3D world yetâto understand more before jumping into the 3D world for the later projects.
There is a huge improvement on Unity after the release of 4.3. The best feature for most game developers is the 2D feature in Unity, which will help us to speed up the 2D game development time. In this project, we will be using a similar concept to the Unity's 2D Platformer project in the assets store. This includes the new sprite object and the new 2D physics engine that integrated Box2D (the 2D physics game engine that is used in many games such as Angry Birds).
Note
We can also download the Unity 2D project from the Unity Asset Store: https://www.assetstore.unity3d.com/#/content/11228
For more information about Box2D, visit the following URLs: http://box2d.org/about/ and http://en.wikipedia.org/wiki/Box2D
We'll be creating a 2D platform or side-scrolling game, which is similar to Mario or other games that we mentioned previously; it will have a simple character that can be made to move, jump, and collect a key item for passing the level, and a Restart button to play the game again. The following screenshot demonstrates this:

We will use a 2D character sprite sheet (which is the set of many small images in a large image, as shown in the previous figure), and the new 2D feature in Unity to create our 2D character. The new 2D feature in Unity helps us to manage the sprite sheet and set up the animation for each character's movement without writing any script.
Note
There are many tools that can help you to create a sprite sheet, such as TexturePacker. It basically creates an image file with the data that contains all the information such as name of the sprite, position, and sprite area. In this process, we will have two filesâthe image file (.jpeg
or .png
) and datafile (.txt
or .xml
)â which might be a bit confusing for beginners. So, Unity 4.3 solved this problem by including the Asset Import Setting, which we can just use to import the asset and set the Texture Type to Sprite, and then set the mode to either Multiple (the image that contains many sprites packed in one file) or Single sprite.
For more information about TexturePacker and a sprite sheet, visit the following URL: http://www.codeandweb.com/texturepacker and http://www.codeandweb.com/what-is-a-sprite-sheet.
The purpose of this project is to familiarize you with the new 2D feature and language syntax in Unity, which is very important when creating a playable game.
We will begin by setting up the sprite for our character, game level, and item in the game. Next, we will create our character sprite object, create the animator controller, and set up each animation clip for idle, walk, jump, and fall. We will also create the script, which will control the character to show the correct animation (idle, walking, and jumping). This script will allow us to control the character action by pressing the arrow key to move and space bar to jump. Also, we will learn how to set up the custom input manager.
Next, we will create the level and platform using the sprite object with BoxCollider2D
and PolygonCollider2D
attached, which will collide with the character that has Rigidbody2D
attached to make the movement realistic.
To end the game, we will create a trigger event by having a door and key game object. The player needs to collect the key to be able to open the door and end the game. We will also add sound to make our game lively, but we are not finishing it yet. The game needs to be replayable. Lastly, we will add a Replay or Play again button to replay our game by using Destroy
and Instantiate
to reset our character's position and key item.
When we are done with this project, we will get a good understanding of how to create a sprite and 2D platform game by using the new 2D feature in the Unity engine. Also, we will be able to create our own 2D platform style game such as Sonic, Mario, and Mega Man, and reuse some of our techniques, scripts, and concepts to create a 3D game at a later stage.
This project will be split into five tasks. As we are not creating any enemies in our game, we don't have to deal with any complex scripting. It will be a simple step-by-step process from beginning to end. The following is the outline of the tasks:
Setting up a 2D level and collider
Creating a 2D character and animation
Controlling the character with the
PlayerController_2D
classesCreating a key, door, and replay button
Before we start, we will need to get the latest Unity version ( http://unity3d.com/unity/download/) that includes MonoDevelop, which we will use for our scripting editor. We will also need a few graphics for our character, key, and door as well as a collection of sound FX. These can be downloaded as ZIP files from Packt's website: http://www.packtpub.com/support?nid=8267.
Browse the preceding URL and download the Chapter1.zip
package and unzip it. Inside the Chapter1
folder, there are two unity packages: Chapter1Package.unitypackage
(we will use this package for this project) and Chapter1Package_Completed.unitypackage
(this is the completed project package that includes both C# and Unity JavaScript).
In this section, we will begin with setting up all sprite assets including the character sprite sheet, background, platform, door, and key sprite. Then, we will create a custom tag and layer to use in our game. Next, we will set up our level by using the sprite game object and attaching the 2D collider including BoxCollider2D
and PolygonCollider2D
.
Before we start creating this project, we will create the project in Unity by performing the following steps:
Create a new project by going to File | New Project to bring up the Project Wizard window. Next, click on the Create new Project tab and set the Project Directory as you want, as we can see in the following screenshot:
As we can see from the preceding screenshot, we don't import any Unity assets package because we won't be using any of those packages in this project. This helps to reduce the size of the project because we don't have any unnecessary assets. We also set up the default of Unity mode to use 2D instead of 3D, which basically will set the camera to use the 2D view instead of the 3D view. It also sets the default asset importing to use Sprite instead of the Texture type.
Tip
By setting the default mode to 2D or 3D in Unity editor, we can go to Edit | Project Settings | Editor and change the Default Behavior Mode to 2D or 3D, as we can see in the following screenshot:
We can also switch between the 2D and 3D views by clicking on the 2D tab in the Scene view, as shown the following screenshot:
Then, go to Assets | Import Package | Custom Package⦠and select the
Chapter1Package.unitypackage
file from the folder that we just unzipped and click on Import to import all assets, as we can see in the following screenshot:To make it easy for us, we will go to SimplePlatform | Scenes in the Project view. We will see there is one scene in this folder named SimplePlatform; double-click to open it as shown in the following screenshot:
We will see that nothing in the Hierarchy has changed. No worries, we will use this scene as our base scene to save all the progress that we will make in this project.
At the last step, we will go to SimplePlatform | Resources | Sprites | Level and click on the Background file inside this folder in the Project view. Then, we will go to the Inspector view, set it as the following screenshot, and click on Apply:
As we can see, this time we set the Sprite Mode to Single. This means that this file only contains one sprite. Now we have finished the setup part. Next, we will start building the level.
To start building the level, first we need to add new tags and layers. So, let's get on with it:
Let's go to Edit | Project Settings | Tags and Layers to bring up the Tags and Layers inspector view and set it as follows:
Tags
Size
5
Element 0
Ground
Element 1
RestartButton
Element 2
Key
Element 3
Door
Layers
User Layer 8
Player
User Layer 9
Ground
Tags make it easy to find the object, we need
GameObject.FindWithTag("TagName")
orgameObject.tag
. More details on tags can be found at http://docs.unity3d.com/Documentation/Components/Tags.html.Note
Layers are used to determine which object will be rendered or used for raycasting. Sometimes, we can use layers to separate the objects to be rendered. For example, we could have two cameras and set the first camera to render only the foreground objects and then another camera to render only the background object (such as, UI, or minimap). More details on layers can be found at http://docs.unity3d.com/Documentation/Components/Layers.html.
Next, we create the background by going to SimplePlatform | Resources | Sprites | Level in the Project view, click on Background file, and drag it to the Hierarchy view, as shown in the following screenshot:
Then, we click on the Background object in the Hierarchy view, go to its Inspector view, and set the parameters as follows:
Layer
Level
Transform
Position
X:
0
, Y:0
, and Z:0
Scale
X:
3
, Y:3
, and Z:1
Sprite Renderer
Color
R:
171
, G:245
, B:255
, and A:255
Order in Layer
-1
Next, we will create the Level empty game object to contain our level by going to GameObject | Create Empty; name it Level, and reset all the transformation to the default value by going to its Inspector view and right-clicking on the gear wheel icon and choosing Reset, as shown in the following screenshot:
Then, we will add the floor and wall by going to SimplePlatform | Resources | Sprites | Level in the Project view and clicking on the arrow in front of the Platform file. Then, we will click on the Floor object and drag it inside the Level game object in the Hierarchy view, and do the same thing with the Wall object, as shown in the following screenshot:
Next, we will click on the Floor object in the Hierarchy view and add Box Collider 2D by going to Component | Physics2D | Box Collider 2D. Then, we will go to Inspector and set the values of the attributes as follows:
Tag
Ground
Layer
Ground
Transform
Position
X:
0
, Y:-9.2
, and Z:0
Scale
X:
5
, Y:5
, and Z:1
Sprite Renderer
Order in Layer
2
Box Collider 2D
Material
Ground (drag the Physics2D Material here)
Then, we duplicate the Floor object by pressing Ctrl + D (on Windows) or command + D (on Mac) and set the second Floor object and change the transform position as follows:
Transform
Position
X:
0.25
, Y:11
, and Z:0
Next, we will set the Wall object, click on this object, and add the Box Collider 2D by going to Component | Physics2D | Box Collider 2D. Then, we will go to Inspector and set it as follows:
Transform
Position
X:
-14
, Y:-1.46
, and Z:0
Scale
X:
5
, Y:5
, and Z:1
Sprite Renderer
Order in Layer
1
Box Collider 2D
Material
Edge (drag the Physics 2D Material here)
Then, we duplicate the Wall object by pressing Ctrl + D (on Windows) or command + D (on Mac) three times and set the second, third, and fourth Wall object and change the transform position as follows:
Transform (second
Wall
object)Position
X:
14
, Y:-1.47
, and Z:0
Transform (third
Wall
object)Position
X:
-17.8
, Y:-1.47
, and Z:0
Transform (forth
Wall
object)Position
X:
17.8
, Y:-1.47
, and Z:0
Now, we will add
LargePlatform
. Let's go to SimplePlatform | Resources | Prefabs in the Project view, and click on the arrow in front of the LargePlatform prefab. Then, we will click on the Platform_5, Platform_4, Platform_6, and Platform_1 objects and set Tag and Layer to Ground. Then, we will drag LargePlatform inside the Level game object in the Hierarchy view, go to its Inspector, and set it as follows:Transform
Position
X:
7.34
, Y:0.7
, and Z:0
Next, we add Platform_1. Let's go to SimplePlatform | Resources | Prefabs in the Project view, click on the Platform_1 object, and set Tag and Layer to Ground. We will see the Change Layer pop up; click on the No, this object only button. Then, we will drag it inside the Level game object in the Hierarchy view, go to its Inspector, and set it as follows:
Transform
Position
X:
9.5
, Y:-4
, and Z:0
Then, we do the same thing for Platform_3. Let's go to SimplePlatform | Resources | Prefabs in the Project view, click on the Platform_3 object, and set Tag and Layer to Ground. We will see the Change Layer pop up; click on the No, this object only button. Then, we will drag it inside the Level game object in the Hierarchy view. Go to Inspector, and set it as follows:
Transform
Position
X:
-6.28
, Y:2.33
, and Z:0
Scale
X:
1.4
, Y:1.4
, and Z:0
Next, we will duplicate Platform_3 by pressing Ctrl + D or command + D to create the second Platform_3 object and set it as follows:
Transform
Position
X:
7.25
, Y:4.53
, and Z:0
Scale
X:
-1.4
, Y:1.4
, and Z:0
We will see the level in the Scene and Hierarchy view similar to the following screenshot:
We can see that we already have the Platform_1 and Platform_3 prefab. Now, we will create the Platform_2 prefab from scratch. First, we will go to SimplePlatform | Resources | Sprites | Level in the Project view and click on the arrow in front of the Platform file. Then, we will click on the Platform_2 object and drag it inside the Level game object in the Hierarchy view. Click on this object and add Polygon Collider 2D by going to Component | Physics2D | Polygon Collider 2D. Then, we will go to Inspector and set the values of the attributes as follows:
Tag
Ground
Layer
Ground
Transform
Position
X:
-7
, Y:-1.17
, and Z:0
Box Collider 2D
Material
Ground (drag the Physics2D Material here)
Now, we go to the Scene view. We will see that our Platform_2 sprite has Polygon Collider 2D that matches the shape of this sprite, as shown in the following screenshot:
From the preceding screenshot, we will see that there are too many vertices for this sprite. So, we need to decrease and adjust the vertices to match the sprite.
Next, we will adjust the vertices in Polygon Collider 2D. To make it easy to adjust, we will go to Platform_2 Inspector and click on the arrow in front of Sprite Renderer to hide the 2D outline gizmos, as shown in the following screenshot:
Now, we will remove the vertices in Collider Info from
50
to7
, which will optimize the content and help the overall performance in the scene. We can do this by pressing Ctrl (on Windows) or command (on Mac) . We will see the red dot. We can now click on the vertex to remove the vertices from50
to7
, similar to the following screenshot:Next, we will adjust the vertices to match the sprite by pressing Shift. We will see the green dot. We can go to each vertex to move it.
Tip
We can also add the vertex by pressing Shift and then clicking on the line.
For more information about Polygon Physics 2D, visit http://docs.unity3d.com/Documentation/Components/class-PolygonCollider2D.html.
We will get the result as shown in the following screenshot (the position of each vertex shows as the circle):
Then, we will create the Edge game object, which is basically to prevent the character from getting stuck on the platform edge. Let's go to GameObject | Create Empty, name it
Edge
, and drag it inside Platform_2.Then, we will add Box Collider 2D to the Edge object by going to Component | Physics2D | Box Collider 2D. Go to Inspector and set it as follows:
Transform
Position
X:
1.47
, Y:-0.2
, and Z:0
Rotation
X:
0
, Y:0
, and Z:333.4
Box Collider 2D
Material
Edge (drag the Physics 2D Material here)
Size
X:
0.21
and Y:0.5
Next, we will duplicate the Edge game object by pressing Ctrl + D or command + D to create the second Edge object and set the values of the attributes as follows:
Transform
Position
X:
-1.52
, Y:-0.02
, and Z:0
Rotation
X:
0
, Y:0
, and Z:9.2
Box Collider 2D
Material
Edge (drag the Physics 2D Material here)
Size
X:
0.21
and Y:0.67
We got our Platform_2 game object. Next, we will create the prefab of this game object by dragging the Platform_2 game object from the Hierarchy view to the SimplePlatform | Resources | Prefabs in the Project view.
Next, we will create two more Platform_2 objects. Let's press Ctrl + D or command + D twice to create the second and third Platform_2 object and change the transform position as follows:
Transform (second
Platform_2
object)Position
X:
-10
, Y:-3.27
, and Z:0
Transform (third
Platform_2
object)Position
X:
-9.25
, Y:-5.87
, and Z:0
Scale
X:
1.3
, Y:1.3
, and Z:1
Finally, we will see the result of our level as the following screenshot, and we are now ready for the next step:
Basically, what we have done here is create a Background object and the Level object, and set each platform that attached Box Collider 2D and Polygon Collider 2D, which we will use to check the collision and make our player walkable on the platform. We also set the Order in Layer in the Sprite Renderer component to get the correct depth from the background to foreground, as shown in the following diagram:

We also adjust and remove the vertices of Polygon Collider 2D by holding the Shift or Ctrl/command key. Then, we create the Edge object that uses a different Physics2D Material from the platform object, which is used to prevent our player from getting stuck on the platform's edge.
In 3D Unity mode, the camera can be set to either Orthographic or Perspective. The difference between both projections is that with the Orthographic Projection, the object won't scale by a factor inversely proportional to the distance from the camera. So in our scene, we will see only one side of the cube that faces the camera. On the other hand, in the Perspective Projection, we will see that the face of the cube will scale down depending on the distance from the camera, which is similar to real life:

On the other hand, in the 2D mode, we won't see any significant difference between Orthographic Projection and Perspective Projection. In some cases, we will see only one side if the cube is directly facing the camera. However, if we want to zoom in or out the 2D camera in the Orthographic Projection, we can only adjust the Size parameter. The Z transform position will not do anything, which is different from the Perspective Projection. We can either adjust the Z transform position or the Field of View parameter to zoom in or out as shown in the following screenshot:

In the Sprite Renderer, we will see that there are two Layer properties, Sorting Layer and Order in Layer, which will help us sort the depth of our sprite and tell Unity which sprite should be drawn first (the lower number will get drawn first). We only use the Order in Layer property to sort the depth of our sprite in the same layer group. So, here's when Sorting Layer comes in handy.
If we go to Edit | Project Settings | Tags & Layers, we will see that there is Sorting Layers. This is the new feature in Unity so that we can set our sprites in this layer group and tell Unity which layer group should be drawn first. For example, we can set the background layer to contain all the background sprites and then set the foreground layer to contain all the foreground sprites. This way we will always know that the foreground sprites will be drawn after the background sprites, as shown in the following screenshot:

For more information about Sprite Renderer and Sorting Layer, visit http://docs.unity3d.com/Documentation/Components/class-SpriteRenderer.html.
In this step, we will start with setting up our sprites. Next, we will create our 2D character from the sprite sheet in our SimplePlatform package. Then, we will create the animator controller and the animation clip for idle, walking, falling, and jumping.
Let's begin with setting up our character from the sprite sheet:
Now, we will go to SimplePlatform | Resources | Sprites | Characters and click on the Spritesheet file inside this folder in the Project view. Then, we will go to the Inspector view, set it as shown the following screenshot, and click on Apply:
In the Inspector view, we click on the Sprite Editor button, which will open the Sprite Editor window. Then, we click on the Slice drop-down button to bring up the Slice window. We will leave the parameters as it is and then click on the Slice button to slice all the sprites as the following screenshot:
Now, we will see the white frame on each sprite, click on the first sprite (on the top-left corner) to bring up the sprite window, and rename from
Spritesheet_0
toWalk_0
, as shown in the following screenshot:Next, we will keep going by clicking on each sprite from top-left to bottom-right corner and rename the sprites as follows:
Sprite name
Renamed sprite
Spritesheet_0
Walk_0
Spritesheet_1
Walk_1
Spritesheet_2
Walk_2
Spritesheet_3
Walk_3
Spritesheet_4
Walk_4
Spritesheet_5
Walk_5
Spritesheet_6
Walk_6
Spritesheet_7
Idle_0
Spritesheet_8
Idle_1
Spritesheet_9
Jump_0
Spritesheet_10
Jump_1
Spritesheet_11
Jump_2
Then, we will click on the Apply button at the top-right corner of the Sprite Editor window, as shown in the following screenshot:
If we go to the Project view, we will see that the Spritesheet file has an arrow in front of it. If we click on the arrow, we see all the sprites that we just renamed, as shown in the following screenshot:
Finally, we will go to SimplePlatform | Resources | PhysicsMaterials in the Project view. We will see that there is Physics2D Material for Ground and Edge, which control Friction and Bounciness between Player and Level. We still need to create one more Physics2D Material player for our player. So, right-click and go to Create | Physics2D Material, name it
Player
, and set Friction to1.2
and Bounciness to0
, as shown in the following screenshot:
Now, we can start creating our character sprite. Let's get started:
Let's go to SimplePlatform | Resources | Sprites | Characters in the Project view and click on the arrow in front of the Spritesheet file. Then, we will click on both the Idle_0 and Idle_1 objects and drag it to the Hierarchy view. We will see the pop-up window asking to create a new animation, set the filename to
Idle
, put it in SimplePlatform | Resources | Sprites | Animation, and click on Save, as shown in the following screenshot:Next, we will go to SimplePlatform | Resources | Sprites | Animation and click on the Idle_0 object and rename it to
PlayerAnimator
.Then, we go back to SimplePlatform | Resources | Sprites | Characters in the Project view and click on the arrow in front of the Spritesheet file. After that, we will click on all Walk objects from Walk_0 to Walk_7 (eight objects in total), and drag them to the Idle_0 game object in the Hierarchy view. We will see the pop-up window asking us to create the new animation again, set the filename to
Walk
, put it in SimplePlatform | Resources | Sprites | Animation, and click on Save.In the Spritesheet file in the Project view, we will click on Jump_0 and Jump_1 and drag them to the Idle_0 game object in the Hierarchy view. We will see the pop-up window asking us to create the new animation again, set the filename to
Jump
, put it in SimplePlatform | Resources | Sprites | Animation, and click on Save.We will do the same as the last step, but this time we will click on Jump_1 and Jump_2, and drag them to the Idle_0 game object in the Hierarchy view. We will see the pop-up window asking us to create the new animation again, set the filename to
Fall
, put it in SimplePlatform | Resources | Sprites | Animation, and click on Save.Next, we will go to SimplePlatform | Resources | Sprites | Animation in the Project view. Then, we will click on the Fall and Jump animation, go to their Inspector view, and uncheck Loop Time for both clips, as shown in the following screenshot:
Then, we go to the Hierarchy view, rename Idle_0 to
Player
, go to its Inspector view, and set the values of the attributes as follows:Tag
Player
Layer
Default
Transform
Position
X:
-10
, Y:4.6
, and Z:0
Animator
Apply Root Motion
Uncheck this option
Culling Mode
Based On Renderers
Next, we will set up PlayerAnimator. Let's go to SimplePlatform | Resources | Sprites | Animation in the Project view and double-click the PlayerAnimator object to bring up the Animator view. Then, we click on each clip and layout the position similar to the following screenshot:
Then, we click on each clip and go to Inspector to set the speed of each animation clip. We will start with the Idle clip and move ahead; let's go to each clip inspector and set it up as follows:
Clip
Speed
Idle
0.15
Walk
0.8
Jump
0.5
Fall
0.5
Next, we will add a few parameters to control when each animation will be played. Let's go to the Parameters tab at the bottom-left corner of the Animator view, click on the plus icon four times, and choose the name and type of parameter as follows:
Name
Type
Speed
Float
Jump
Trigger
Fall
Trigger
Ground
Trigger
These parameters will be used as a condition to control the changing state of each animation clip on our character.
Next, we will create the transition between each animation state. First, we will start with our base animation Idle and transition to Walk. Right-click on the Idle clip and choose Make Transition, which will bring up the arrow, and click-and-drag again on top of the Walk clip. We will see the arrow line link from the Idle clip to the Walk clip, as shown in the following screenshot:
Then, we want to click on the arrow line that we just created and go to Inspector | Conditions and set Speed to a value greater than 0.1.
Next, we will create the transition back from the Walk to Idle animation. So, let's right-click on the Walk clip, choose Make Transition, and then click-and-drag on Idle. Then, we will click on the arrow line again to go to the Inspector and set a value less than 0.1 for Speed in the Conditions view.
Then, we set up the rest of the animation. This time we want the transition from Walk to Fall. So, let's right-click on the Walk clip, choose Make Transition, and then click-and-drag on Fall. After that, we will click on the arrow line again to go to Inspector and set the Conditions view to Fall.
Also, we will create the transition from Fall back to Walk, go to the transition Inspector, click on the plus icon to add another condition and set Speed as well as Ground to a value greater than 0.1.
Next, we want the Idle clip transition to Fall. Let's create the transition arrow from Idle to Fall, go to Inspector, and set the Conditions view to Fall.
We also need to create the transition from Fall back to Idle, set up its Inspector view, click on the plus icon to add another condition, and set Speed to a value less than 0.1.
Then, we will create the transition arrow from Idle to Jump and set up its Inspector view by setting its Conditions view to Jump.
Next, we create the transition arrow from Walk to Jump and set up its Inspector view by setting its Conditions view to Jump.
Then, we need the transition arrow from Jump to Fall and set up its Inspector view by setting its Conditions view to Fall.
The current Animator view will look similar to the following screenshot:
Finally, we will need to attach Rigidbody 2D and Box Collider 2D to our Player game object. Let's go back to the Hierarchy view, click on the Player game object, go to Component | Physics 2D | Rigidbody 2D to add Rigidbody 2D, go to Component | Physics 2D | Box Collider 2D to add Box Collider 2D, and then set up Inspector as follows:
Rididbody 2D
Fixed Angle
Check the box
Interpolate
Interpolate
Box Collider 2D
Material
Player (drag the Physics2D Material here)
Tip
Rigidbody â Mass and Drag / Rigidbody2D â Mass and Linear Drag
In Unity Rigidbody or Rigidbody2D, Mass doesn't make the object fall faster or slower. The speed of the object will depend on gravity and drag. Mass will only be used when the object is colliding with another, as the higher mass will push the lower mass more. (Make sure you keep Mass between 0.1 and never more than 10). The links to the documentation are as follows: http://docs.unity3d.com/Documentation/ScriptReference/Rigidbody2D-mass.html and http://docs.unity3d.com/Documentation/ScriptReference/Rigidbody-mass.html.
Drag or Linear Drag can be used to slow down the object. The higher the drag, the more the object will slow down. The links to the documentation are as follows: http://docs.unity3d.com/Documentation/ScriptReference/Rigidbody2D-drag.html and http://docs.unity3d.com/Documentation/ScriptReference/Rigidbody-drag.html.
We just set up the Player sprite from the Spritesheet file that included multiple sprites by using the Unity Sprite Import Settings to slice each sprite and rename it to make it easier to use in each animation clip. We also create the animator controller, which is a part of the Mecanim animation system, to switch the state between each animation clip by using the float value and trigger condition.
The Mecanim animation system is the new animation system in Unity, which helps us to simplify the complex interactions between each animation with a visual programming tool. It also provides an easy workflow to set up the humanoid character animation. For more information on the Mecanim animation system, visit http://docs.unity3d.com/Documentation/Manual/MecanimAnimationSystem.html.
We will get in more details about Mecanim in Project 4, Add Character Control and Animation to Our Hero/Heroine.
Finally, we add RigidBody 2D and Box Collider 2D to our player. Then, we tell Rigidbody 2D to use the Fixed Angle and Interpolate mode. Also, we set the Box Collider 2D Material to use the Player Physics 2D Material that we've created.
Tip
Fixed Angle and Interpolate mode
Why do we need to perform Fixed Angle of RigidBody 2D? Is this also similar to the freezing of the rotation and position of Rigidbody? To use Fixed Angle of RigidBody 2D, we basically tell Unity that it will ignore the calculation of the rotation of the object. This will make our character always stay at the same angle while moving. In this way, we can also save the CPU cycles because Unity will ignore the unnecessary calculation and only calculate the one it needs. For the Interpolate mode, we've set it to Interpolate to ensure smooth motion, which use the object's position of the previous frame to calculate the next position. This will also prevent jerky movement. For more information on Interpolate, visit http://docs.unity3d.com/Documentation/ScriptReference/Rigidbody2D-interpolation.html.
In this step, we create the Player physics 2D material object and assign it to Box Collider 2D for our Player game object. So, what is Physics2D Material? If we take a close look at the inspector of the Physics2D Material object, we will see that there are two properties: Friction and Bounciness. Friction is the force that resists the relative motion of this collider. Bounciness is the degree to which collisions rebound from the surface (0
means no bounce and 1
means perfect bounce with no loss energy).
Note
For more details of Physics2D Material, visit http://docs.unity3d.com/Documentation/Components/class-PhysicsMaterial2D.html.
We've set Friction for the Player physics 2D material to 1.2
, which means that we will use 1 to calculate the coefficient of friction in this collider. If we remember the previous step, we also assigned the Edge and Ground physics 2D material object on our platform and edge. If we take a look at the Ground physics 2D material's Friction value, we will see that the value is equal to 1. This means that when we stop moving our character, there won't be any much force left to push the character forward.
On the other hand, the
Edge physics 2D material object has the Friction value set to 0
, which means that there is no friction in this collider. So, it will result our character not being able to stop on this collider. This helps us to prevent our character from getting stuck on the edge of the platform, as shown in the following screenshot:

In this section, we will create a new script to control the movement of our character and a sprite animation for each action of our character. We will use MonoDevelop as our scripting editor, which comes with Unity. MonoDevelop is mainly designed for the C# and .NET environments, so if you are comfortable with C#, you will probably love it. However, if you use Unity JavaScript, it also has many tools to help us write the script faster and debug better, such as finding as well as replacing words in the whole project by pressing command + Shift + F in Mac or Ctrl + Shift + F in Windows and autocomplete (or Intellisense), to name a few. Moving from Unity JavaScript to C# or C# to Unity JavaScript is also a comparatively smooth transition.
Note
In this version of this book, we will show examples for both Unity JavaScript and C#. You can check out the major difference between Unity JavaScript and C# in the Appendix C, Major differences Between C# and Unity JavaScript.
Now, we are just about to start coding, but first let's make sure that we have everything ready:
Next, we want to make sure that Unity uses MonoDevelop as our main Scripting editor (Unity | Preferences in Mac or Edit | Preferences in Windows).
We will see a Unity Preferences window. In the External Tools tab, go to the External Script Editor and make sure that the MonoDevelop option is selected. Click on Browseâ¦, go to Applications | Unity | MonoDevelop.app in Mac or {unity install path} | Unity | MonoDevelop | MonoDevelop.exe in Windows, and we are done:
If we develop a game for Android, we can also set the Android SDK Location path here as shown in the previous screenshot.
Now, we are ready to create the PlayerController_2D
script. Let's get started:
First, go to Assets | Create | Javascript (for Unity JavaScript developers) or Assets | Create | C# Script (for C# developers) and name our script as
PlayerController_2D
.Double-click on the script; it will open the MonoDevelop window.
Now, we will see three windows in the MonoDevelop screen:
On the top-left is Solution; we can see our project folder here, but it will only show the folder that contains a script
On the bottom-left, we will see a Document Outline; this window will show all the functions, classes, and parameters in the file
The last window on the right will be used to type our code
Let's get our hands dirty with some codeâfirst start with defining the following functions to initialize the variables: the
Awake()
andStart()
function.Tip
Awake ()
Awake
()
is called when the script instance is being loaded. It used to initialize any variable or game state before calling theStart()
function. In theAwake()
function, we usually put anyGetComponent()
orFind()
object function, which will make it easier to set up all the parameters duringStart()
.We need to remove the autogenerated code and replace it with the following code:
// Unity JavaScript user: #pragma strict @script RequireComponent(AudioSource) @script RequireComponent(BoxCollider2D) @script RequireComponent(Rigidbody2D) // Distance from the character position to the ground private final var RAYCAST_DISTANCE : float = 0.58f; // This number should be between 0.35 to 0.49 private final var CHARACTER_EDGE_OFFSET : float = 0.40f; var doorOpenSound : AudioClip; var getKeySound : AudioClip; var jumpSound : AudioClip; var moveForce : float = 80f; var jumpForce : float = 350f; var maxSpeed : float = 3f; var layerMask : LayerMask; private var _animator : Animator; private var _boxCollider2D : BoxCollider2D; private var _isFacingRight : boolean = true; private var _isJump : boolean = false; private var _isFall : boolean = false; private var _isGrounded : boolean = false; private var _gameEnd : boolean = false; private var _height : float; private var _lastY : float; private var _horizontalInput : float; function Awake() { _animator = GetComponent.<Animator>(); _boxCollider2D = GetComponent.<BoxCollider2D>(); _height = _boxCollider2D.size.y; } function Start () { _isFacingRight = true; _isJump = false; _isFall = false; _isGrounded = false; _gameEnd = false; _lastY = transform.position.y; Camera.main.transform.position = new Vector3(transform.position.x, transform.position.y, Camera.main.transform.position.z); }
Note
#pragma strict
In Unity JavaScript, we can use
#pragma strict
to tell Unity to disable dynamic typing (var name = 5
) and force us to use static typing (var name : int = 5
). This will make it easy for us to debug. For example, if we forgot to use static typing, you will see an error message from the Unity console window. Using strict typing also makes the code run faster as the complier doesn't have to go and do the type lookups.// C# user: using UnityEngine; using System.Collections; [RequireComponent(typeof(AudioSource))] [RequireComponent(typeof(BoxCollider2D))] [RequireComponent(typeof(Rigidbody2D))] public class PlayerController_2D : MonoBehaviour { // Distance from the character position to the ground const float RAYCAST_DISTANCE = 0.58f; // This number should be between 0.35 to 0.49 const float CHARACTER_EDGE_OFFSET = 0.40f; public AudioClip doorOpenSound; public AudioClip getKeySound; public AudioClip jumpSound; public float moveForce = 80f; public float jumpForce = 350f; public float maxSpeed = 3f; public LayerMask layerMask; Animator _animator; BoxCollider2D _boxCollider2D; bool _isFacingRight = true; bool _isJump = false; bool _isFall = false; bool _isGrounded = false; bool _gameEnd = false; float _height; float _lastY; float _horizontalInput; void Awake() { _animator = GetComponent<Animator>(); _boxCollider2D = GetComponent<BoxCollider2D>(); _height = _boxCollider2D.size.y; } void Start () { _isFacingRight = true; _isJump = false; _isFall = false; _isGrounded = false; _gameEnd = false; _lastY = transform.position.y; Camera.main.transform.position = new Vector3(transform.position.x, transform.position.y, Camera.main.transform.position.z); } }
Tip
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Note
@script RequireComponent(Component)
and[RequireComponent(typeof(Component))]
We add
RequireComponent
to force the script to automatically add the required component as a dependency when adding this class to the game object. For more details, visit http://docs.unity3d.com/Documentation/ScriptReference/RequireComponent.html.Next, we will add the
Flip()
function after theStart()
function to make our character sprite show the correct graphics when moving left or right. The code for Unity JavaScript and C# users are as follows:// Unity JavaScript user: private function Flip () { _isFacingRight = !_isFacingRight; var scale : Vector3 = transform.localScale; scale.x *= -1; transform.localScale = scale; } // C# user: (Put the code inside the class) void Flip () { _isFacingRight = !_isFacingRight; Vector3 scale = transform.localScale; scale.x *= -1; transform.localScale = scale; }
Next, we will add another function, which will use
Physics2D.Raycast
to check whether the player is on the ground or not. Let's create theGrounded()
function as follows:// Unity JavaScript user: private function Grounded () { var distance : float = _height*RAYCAST_DISTANCE; var hitDirectionV3 : Vector3 = transform.TransformDirection(-Vector3.up); var hitDirection : Vector2 = new Vector2(hitDirectionV3.x,hitDirectionV3.y); var rightOrigin : Vector2 = new Vector2(transform.position.x + (_boxCollider2D.size.x*CHARACTER_EDGE_OFFSET), transform.position.y); var leftOrigin : Vector2 = new Vector2(transform.position.x - (_boxCollider2D.size.x*CHARACTER_EDGE_OFFSET), transform.position.y); var origin : Vector2 = new Vector2(transform.position.x, transform.position.y); if (Physics2D.Raycast (origin, hitDirection, distance, layerMask.value)) { _isGrounded = true; } else if (Physics2D.Raycast (rightOrigin, hitDirection, distance, layerMask.value)) { _isGrounded = true; } else if (Physics2D.Raycast (leftOrigin, hitDirection, distance, layerMask.value)) { _isGrounded = true; } else { if (_isGrounded) { if (Mathf.Floor(transform.position.y) == _lastY) { _isGrounded = true; } else { _isGrounded = false; } } } _lastY = Mathf.Floor(transform.position.y); } // C# user: (Put the code inside the class) void Grounded () { float distance = _height*RAYCAST_DISTANCE; Vector3 hitDirectionV3 = transform.TransformDirection (-Vector3.up); Vector2 hitDirection = new Vector2(hitDirectionV3.x,hitDirectionV3.y); Vector2 rightOrigin = new Vector2(transform.position.x + (_boxCollider2D.size.x*CHARACTER_EDGE_OFFSET), transform.position.y); Vector2 leftOrigin = new Vector2(transform.position.x - (_boxCollider2D.size.x*CHARACTER_EDGE_OFFSET), transform.position.y); Vector2 origin = new Vector2(transform.position.x, transform.position.y); if (Physics2D.Raycast (origin, hitDirection, distance, layerMask.value)) { _isGrounded = true; } else if (Physics2D.Raycast (rightOrigin, hitDirection, distance, layerMask.value)) { _isGrounded = true; } else if (Physics2D.Raycast (leftOrigin, hitDirection, distance, layerMask.value)) { _isGrounded = true; } else { if (_isGrounded) { if (Mathf.Floor(transform.position.y) == _lastY) { _isGrounded = true; } else { _isGrounded = false; } } } _lastY = Mathf.Floor(transform.position.y); }
Next, we will include the script in the
Update()
function andLateUpdate()
function that get called after theUpdate()
function. These functions will be used to check the input from the user and update the camera to follow our character movement. The code for these functions are as follows:// Unity JavaScript user: function Update() { if (!_gameEnd) { _horizontalInput = Input.GetAxis("Horizontal"); if ((!_isFacingRight && (_horizontalInput > 0)) || (_isFacingRight && (_horizontalInput < 0))) { Flip(); } Grounded(); if(Input.GetButtonDown("Jump") && _isGrounded) { _isJump = true; } } } function LateUpdate() { if (!_gameEnd) { Camera.main.transform.position = new Vector3(transform.position.x, transform.position.y, Camera.main.transform.position.z); } } // C# user: (Put the code inside the class) void Update() { if (!_gameEnd) { _horizontalInput = Input.GetAxis("Horizontal"); if ((!_isFacingRight && (_horizontalInput > 0)) || (_isFacingRight && (_horizontalInput < 0))) { Flip(); } Grounded(); if(Input.GetButtonDown("Jump") && _isGrounded) { _isJump = true; } } } void LateUpdate() { if (!_gameEnd) { Camera.main.transform.position = new Vector3(transform.position.x, transform.position.y, Camera.main.transform.position.z); } }
Then, we create a
FixedUpdate()
function, which will handle the animation state changing (Idle, Walk, Jump, or Fall) and add force to move our character horizontally and vertically. Let's add this function as follows:// Unity JavaScript user: function FixedUpdate () { if (!_gameEnd) { _animator.SetFloat("Speed", Mathf.Abs(_horizontalInput)); var xSpeed : float = Mathf.Abs(_horizontalInput * rigidbody2D.velocity.x); if (xSpeed < maxSpeed) { rigidbody2D.AddForce(Vector2.right * _horizontalInput * moveForce); } if (Mathf.Abs(rigidbody2D.velocity.x) > maxSpeed) { var newVelocity : Vector2 = rigidbody2D.velocity; newVelocity.x = Mathf.Sign(newVelocity.x) * maxSpeed; rigidbody2D.velocity = newVelocity; } if(_isJump) { _animator.SetTrigger("Jump"); audio.volume = 0.3f; audio.PlayOneShot(jumpSound); rigidbody2D.AddForce(new Vector2(0f, jumpForce)); _isJump = false; } if (!_isGrounded) { if ((rigidbody2D.velocity.y <= 0f) && !_isFall) { _animator.SetTrigger("Fall"); _isFall = true; } } if (_isGrounded) { if (_isFall) { _animator.SetTrigger("Ground"); _isFall = false; } else { var animationStateInfo : AnimatorStateInfo = _animator.GetCurrentAnimatorStateInfo(0); if ((rigidbody2D.velocity.y < 0f) && (animationStateInfo.IsName("Base Layer.Jump"))) { _animator.SetTrigger("Fall"); _isFall = true; } } } } } // C# user: (Put the code inside the class) void FixedUpdate () { if (!_gameEnd) { #region Setting player horizontal movement _animator.SetFloat("Speed", Mathf.Abs(_horizontalInput)); float xSpeed = Mathf.Abs(_horizontalInput * rigidbody2D.velocity.x); if (xSpeed < maxSpeed) { rigidbody2D.AddForce(Vector2.right * _horizontalInput * moveForce); } if (Mathf.Abs(rigidbody2D.velocity.x) > maxSpeed) { Vector2 newVelocity = rigidbody2D.velocity; newVelocity.x = Mathf.Sign(newVelocity.x) * maxSpeed; rigidbody2D.velocity = newVelocity; } #endregion #region If the player should jump if(_isJump) { _animator.SetTrigger("Jump"); audio.volume = 0.3f; audio.PlayOneShot(jumpSound); rigidbody2D.AddForce(new Vector2(0f, jumpForce)); _isJump = false; } #endregion #region If the player should fall if (!_isGrounded) { if ((rigidbody2D.velocity.y <= 0f) && !_isFall) { _animator.SetTrigger("Fall"); _isFall = true; } } #endregion #region If the player is grounded if (_isGrounded) { if (_isFall) { _animator.SetTrigger("Ground"); _isFall = false; } else { AnimatorStateInfo animationStateInfo = _animator.GetCurrentAnimatorStateInfo(0); if ((rigidbody2D.velocity.y < 0f) && (animationStateInfo.IsName("Base Layer.Jump"))) { _animator.SetTrigger("Fall"); _isFall = true; } } } #endregion } }
Tip
#region YourComment - #endregion
In C#, we can put any script between
#region Your Code Discription
and#endregion
to specify a block of code that we can expand or collapse by clicking on the plus and minus sign in MonoDevelop.We can see how to use
#region â¦.. #endregion
in the following screenshot:Lastly, we will add the
OnDrawGizmos()
function in this class. It is a very nice function that allows us to debug the game, the result of which we won't see in the real game. Let's add the following block of code:// Unity JavaScript user: function OnDrawGizmos() { _boxCollider2D = GetComponent.<BoxCollider2D>(); _height = _boxCollider2D.size.y; var distance : float = (_height * RAYCAST_DISTANCE); var rightOrigin : Vector3 = new Vector3(transform.position.x + (_boxCollider2D.size.x*CHARACTER_EDGE_OFFSET), transform.position.y, transform.position.z); var leftOrigin : Vector3 = new Vector3(transform.position.x - (_boxCollider2D.size.x*CHARACTER_EDGE_OFFSET), transform.position.y, transform.position.z); Gizmos.color = Color.red; Gizmos.DrawRay(transform.position, transform.TransformDirection (-Vector3.up) * distance); Gizmos.DrawRay(rightOrigin, transform.TransformDirection (-Vector3.up) * distance); Gizmos.DrawRay(leftOrigin, transform.TransformDirection (-Vector3.up) * distance); } // C# user: (Put the code inside the class) void OnDrawGizmos() { _boxCollider2D = GetComponent<BoxCollider2D>(); _height = _boxCollider2D.size.y; float distance = (_height * RAYCAST_DISTANCE); Vector3 rightOrigin = new Vector3(transform.position.x + (_boxCollider2D.size.x*CHARACTER_EDGE_OFFSET), transform.position.y, transform.position.z); Vector3 leftOrigin = new Vector3(transform.position.x - (_boxCollider2D.size.x*CHARACTER_EDGE_OFFSET), transform.position.y, transform.position.z); Gizmos.color = Color.red; Gizmos.DrawRay(transform.position, transform.TransformDirection (-Vector3.up) * distance); Gizmos.DrawRay(rightOrigin, transform.TransformDirection (-Vector3.up) * distance); Gizmos.DrawRay(leftOrigin, transform.TransformDirection (-Vector3.up) * distance); }
Now, save it and go back to Unity; drag-and-drop the PlayerController_2D script to Player, click on Player, and go to the Inspector window. Click on Idle Sprite and Walk Sprite to expand it and then set the following:
Player Controller_2D (Script)
Door Open Sound
doorOpen
Get Key Sound
getkey
Jump Sound
jump
Layer Mask
Ground
Yes! We are done. Let's click on the Play button to play the game. We will see our player moving his hand back and forth. Next, press the A or left arrow / D or right arrow to move the player to the left or to the right; now we see that he is walking. We can also press the Space bar to make our character jump. Isn't that cool?
We just created a script that controls the movement of our character and his animation. First, we created the parameters to use in our script. We also used the const
keyword in C# and the final
keyword in Unity JavaScript to create the constant variables.
Note
The const
and final
keywords
We used the const
keyword in C# to specify that the value of the field or local variable is constant, which means it can't be modified from anywhere else.
However, there is no const
keyword in Unity JavaScript, so we use the final
keyword instead; there is a slight difference between the final
and const
keywords. The const
keyword can only applied to a field whose value is to be known at compile time, such as const
float
. So, this means that we can't use the const
keyword with Vector3
, Rect
, Point
, and all the struct that are included in Unity. On the other hand, we will use readonly
instead. However, the final
keyword can be used in the both cases.
For more details, visit http://tutorials.csharp-online.net/CSharp_FAQ%3A_What_are_the_differences_between_CSharp_and_Java_constant_declarations.
Then, we get _animator
, _boxCollider2D
, and _height
in the Awake()
function to check the animation state while it is moving. Then, we set all the variables to their default value. Next, we created the Flip()
function, which will set _isFacingRight
to true
or false
depending on the character movement. This function also sets the local x
scale to 1
if the character is facing right and -1
if it's facing left.
The next function that we created is the Grounded()
function that uses Physics2D.Raycast
to check whether our character is on the ground or not.
In the Update()
function, we get the character's horizontal movement by using Input.GetAxis("Horizontal")
. Then, we check for the movement direction and call the Flip()
function. After that, we call the Grounded()
function to check whether the character is on the ground or not. If not, we can make the character jump by using Input.GetButtonDown("Jump")
. Next, we update our camera position by using Camera.main
to get access to the Main Camera object and set its position relative to Player.
In the FixedUpdate()
function, we change the animation state from Idle to Walk by using _animator.SetFloat("Speed", Mathf.Abs(_horizontalInput));
. Next, we get the x
speed and check that the speed is lower than the maximum speed. Then, we add the force to Rigidbody2D by using rigidbody2D.AddForce(Vector2.right * _horizontalInput * moveForce);
. We also make sure that the velocity doesn't reach the maximum limit after adding the force by assigning newVelocity
to rigidbody2D.velocity
.
Next, we trigger the jump animation state by using _animator.SetTrigger("Jump");
. We also add the force to make our character jump using rigidbody2D.AddForce(new Vector2(Of,jumpForce);
. Then, we trigger the fall animation state by using _animator.SetTrigger("Fall");
. We also trigger the ground animation state by using _animator.SetTrigger("Ground");
if our character is falling.
Then, we check for the current animation state by getting animatorStateInfo
using _animator.GetCurrentAnimatorStateInfo(0);
. Then, if the current state is the jump state and y
velocity lower than 0
, we will change the animation state to the fall state using if ((rigidbody2D.velocity.y < 0) && (animationStateInfo.IsName("BaseLayer.Jump"))
.
At last, we use the OnDrawGizmos()
function to see the visual of the ray that was drawn in the Grounded()
function using Physics2D.Raycast
. We can also use this function to debug the game without removing any code when releasing the game. Because all the code in the OnDrawGizmos()
function won't be shown in the real game, it's a convenient way to debug our game. As we can see from the following figure, the red arrows represent where the raycast is, which will only show in the scene view:

In Unity, we can set a custom Input Manager by going to Edit | Project Settings | Input. In Inspector, click on Axes and you will see that the value of Size is 15
, which is the array length of all the inputs. If we want more than 15 inputs, we can put the number here (the default is 15
). Next, we will see all 15 names from Horizontal to Jump as a default setting. Each one will have its own parameters, which we can set up as follows:

For more information of each parameter, go to the following link: http://docs.unity3d.com/Manual/class-InputManager.html.
The Negative
Button and Positive Button here will send the negative and positive value, which in most cases is used to control directions such as, left, right, up, and down. There is a Dead parameter, which will set any number that is lower than this parameter to 0
, which is very useful when we use a joystick.
Also, setting Type to Key or Mouse Button and enabling the Snap parameter will reset axis values to zero after it receives opposite inputs.
If we take a look at the Grounded()
function and check out the following highlighted code, we will see that we have cast the ray a bit longer than the sprite collider:
if (Physics2D.Raycast (origin, hitDirection, distance, layerMask.value)) { _isGrounded = true; } else if (Physics2D.Raycast (rightOrigin, hitDirection, distance, layerMask.value)) { _isGrounded = true; } else if (Physics2D.Raycast (leftOrigin, hitDirection, distance, layerMask.value)) { _isGrounded = true; }
From the highlighted code, we draw
Raycast
from the middle of our character downward by 0.58
units. Why don't we set it to 0.5
? We set it this way to make our character stay on the edge of the floor surface. If we set it to 0.5
, we will see that the character will not hit the ground. This is because of the way Box Collider 2D and Polygon Collider 2D detect other collider objects in Unity, as we can see in the following screenshot:

One last thing for Gizmos
: if we want to see our gizmos in the game scene, we can click on the Gizmos tab on the top-right corner of the game scene:

In this step, we will create the end point (door). We will also create a trigger Collider
, which will check for the condition that if the player collected the item, he/she can win the game; of course, the item's the key to open our door. At last, we will create the restart button so that we can restart the game after the game ends.
Let's make sure that we have the sound effects setting correct by going to the SimplePlatform | Resources | Sound folder in the Project view. We will see buttonClick.aiff, doorOpen.wav, getKey.aiff, and jump.wav. Unity, by default, translates every sound that we import in our project to 3D, but we don't really need it as we are creating a 2D game. So, we will click on each sound in the Sound folder in the Project view, go to their Inspector window, and make sure that the 3D Sound is unchecked. If not, uncheck it and click on the Apply button:

Here, we will create the object's Key and Door object first, and then we will create the RestartButton using GUITexture. Let's do this as follows:
Let's go to SimplePlatform | Resources | Sprites | Level in the Project view and drag the Key object to the Hierarchy view. At the Hierarchy view, we will click on the Key game object and then go to Component | Physics 2D | Circle Collider 2D to add the Circle Collider 2D component. Next, we will go to its Inspector view, and set it as follows:
Tag
Key
Transform
Position
X:
10
, Y:-2
, and Z:0
Scale
X:
0.7
, Y:0.7
, and Z:1
Sprite Renderer
Color
R:
255
, G:142
, B:0
, and A:255
Circle Collider 2D
Is Trigger
Check the box
Next, we click on the Key game object in the Hierarchy view and drag inside SimplePlatform | Resources | Prefabs in the Project view to create the Key prefab object.
Then, we will create the Door game object by going to SimplePlatform | Resources | Sprites | Level in the Project view and dragging the DoorClose object to the Hierarchy view. At the Hierarchy view, we will click on the DoorClose game object, go to Component | Physics 2D | Box Collider 2D, and then go to Component | Miscellaneous | Animator.
Next, we will click on the DoorClose game object, rename it to
Door
, and go to Inspector, and set it as follows:Tag
Door
Transform
Position
X:
0.65
, Y:-2.38
, and Z:0
Scale
X:
1.5
, Y:1.5
, and Z:1
Circle Collider 2D
Is Trigger
Check the box
Animator
Controller
DoorAnimator
Apply Root Motion
Uncheck the box
Culling Mode
Based On Renderers
Now we've got the Key and Door game object. We need to go back to the PlayerController_2D script and add a function to make this work. Let's open the PlayerController_2D script and add the
OnTriggerEnter2D()
function as shown in the following highlighted script:// Unity JavaScript user: private var _hasKey : boolean = false; ⦠function Start () { ⦠_hasKey = false; } ⦠function OnTriggerEnter2D (hit : Collider2D) : IEnumerator { if (!_gameEnd) { if (hit.tag == "Key") { if (!_hasKey) { _hasKey = true; audio.volume = 1.0f; audio.PlayOneShot(getKeySound); Destroy (hit.gameObject); } } if (hit.tag == "Door") { if (_hasKey) { _gameEnd = true; _animator.enabled = false; audio.volume = 1.0f; audio.PlayOneShot(doorOpenSound); var doorAnimator : Animator = hit.GetComponent.<Animator>(); doorAnimator.SetTrigger("DoorOpen"); yield WaitForSeconds(1); doorAnimator.SetTrigger("DoorClose"); Destroy (gameObject); } } } } // C# user: (Put the code inside the class) bool _hasKey = false; ⦠void Start () { ⦠_hasKey = false; } ⦠IEnumerator OnTriggerEnter2D (Collider2D hit) { if (!_gameEnd) { if (hit.tag == "Key") { if (!_hasKey) { _hasKey = true; audio.volume = 1.0f; audio.PlayOneShot(getKeySound); Destroy (hit.gameObject); } } if (hit.tag == "Door") { if (_hasKey) { _gameEnd = true; _animator.enabled = false; audio.volume = 1.0f; audio.PlayOneShot(doorOpenSound); Animator doorAnimator = hit.GetComponent<Animator>(); doorAnimator.SetTrigger("DoorOpen"); yield return new WaitForSeconds(1); doorAnimator.SetTrigger("DoorClose"); Destroy (gameObject); } } } }
Next, we click on the Player game object in the Hierarchy view and drag the object inside SimplePlatform | Resources | Prefabs in the Project view to create the Player prefab object.
Inside SimplePlatform | Resources | Prefabs in the Project view, we will see the RestartButton_C# and RestartButton_JS prefab. Now, we will create a new RestartButton from those prefabs, drag the RestartButton_C# prefab (for C# user), and drag the RestartButton_JS prefab (for Unity JavaScript user) to the Hierarchy view.
Then, let's click on the RestartButton prefab, go to its Inspector view, and set the values of the attributes as follows:
Tag
RestartButton
Texture Button (Script)
Key
Drag the
Key
prefab object from theProject
viewPlayer
Drag the
Player
prefab object from theProject
viewFor the last step, we will go back to the PlayerController_2D script and the
_restartButton
variable to make this work. Let's open the PlayerController_2D script and add theOnTriggerEnter2D()
function as shown in the highlighted script:// Unity JavaScript user: ⦠private var _restartButton : GUITexture; ⦠function Awake () { ⦠_restartButton = GameObject.FindWithTag("RestartButton").guiTexture; } function Start () { ⦠_restartButton.enabled = false; } ⦠function OnTriggerEnter2D (hit : Collider2D) : IEnumerator { if (!_gameEnd) { ⦠if (hit.tag == "Door") { if (_hasKey) { ⦠_restartButton.enabled = true; } } } } // C# user: (Put the code inside the class) ⦠GUITexture _restartButton; ⦠void Awake () { ⦠_restartButton = GameObject.FindWithTag("RestartButton").guiTexture; } void Start () { ⦠_restartButton.enabled = false; } ⦠IEnumerator OnTriggerEnter2D (Collider2D hit) { if (!_gameEnd) { ⦠if (hit.tag == "Door") { if (_hasKey) { ⦠_restartButton.enabled = true; } } } }
Ok, now we are done; click on Play to see what we have. Now, when we collect the key and go inside the door, we will see a Restart button appear; click on this button and the game will restart.
We just created a Key and Door object and placed them in our level. We also created the function that will trigger when the character hits the Key and Door objects. For the Door object, we used DoorAnimator for Animator Controller. If we double-click on DoorAnimator and check the Animator view, we will see that there are only two animation states and two trigger parameters to switch between the opening and closing of the door, which is a concept similar to PlayerAnimator, as shown in the following screenshot:

We switched the state to DoorOpen when the character got the Key object and hit the Door object. Then, we waited for one second to remove our character from the scene and switch animation back to DoorClose by using Yield and Destroy.
Lastly, we added the RestartButton prefab to the scene. This prefab is the GUITexture object, which we can click to reset the game after the player goes to the door.
In our script, we need to wait for a second between opening the door and ending the game. We could do this by looping or performing some other task for a second, but that would stop the animations, the sound, and everything else. We get around this by using the yield
command and the Coroutines()
function.
The yield
command tells Unity to stop running our function and come back later (in our game, one second later as we call yield WaitForSecond(1)
(Unity JavaScript) or yield return new WaitForSecond(1)
(C#). By using the yield
command, our function becomes Coroutines
and now it must return IEnumerator
(Unity needs this so that it can tell when to start our function again). This means Coroutines can't return a value like a normal function. We can change most functions in our MonoBehaviours
script into Coroutines
, apart from the ones that already run in every frame, such as Update()
, FixedUpdate()
, and OnGUI()
. We can get more information about Coroutines from the following Unity script reference: http://unity3d.com/support/documentation/ScriptReference/Coroutine.html
If we take a look at the TextureButton
script, we will see that it uses the mouse event function, which will check for the mouse roll over, mouse roll out, and mouse up events. In the OnMouseUp()
function, we will see that we create the new player and key by using Instantiate
to clone both prefab objects and set it back in the scene.
We can also add Application.LoadLevel(LevelName)
to reset our game, which is much easier than using Instantiate
, but Application.LoadLevel
will destroy all the game objects in the scene and reload again.
In this case, we use Instantiate
in our game because we only have one scene and don't want to load the whole game level again. However, we can also put DontDestroyOnLoad()
in the Awake()
function of the object that we don't want to destroy, but it needs a bit of setting up. So, there is no right or wrong. It depends on what we want to use or where we want the project to go.
We just created a simple 2D platform game, and it is our first piece in getting started with Unity. In this project, we learned how to manage a sprite animation by using the new 2D feature in Unity and the Animator Controller from the Mecanim Animation system. We have gone through the MonoDevelop scripting editor. Also, we learned the basics of how to use Input Manager, Physics2D Raycast, Gizmos, and Collider2D. Finally, we attached the sound effect and a Restart button to our game. Let's take a look at what we have:

Now we have a game that looks good, but it's not complete yet. So, why don't you try to do something by using the knowledge gained from this project to add more fun to your game and make it look better? Let's try the following:
Add a background music and more sound effects
Design a challenging level, such as create a movable platform, collect more items at open the door, or even have a longer level
Add obstacles that can make your character die, lose hit points, or restart to another position
Add hit point for our character
Create an animated background or level by using the sprite
Create a parallax background by adding more layers for the background or foreground objects