© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2022
M. KillickThe Way We Playhttps://doi.org/10.1007/978-1-4842-8789-7_8

8. 2D Platformer Tutorial

Michael Killick1  
(1)
Cambridge, UK
 

For this chapter, you will now be shown how you can create the basics of a 2D platformer within Unity which can be used as the foundations for a future project or your first game. To set this project up, you will need to follow a similar process to the 3D first-person project from earlier in this book.

Set Up

If you haven’t done so already, you will need to download Unity Hub which is the home for all updates, your projects, and installations of Unity. You can find this download from the Unity website.

Once downloaded and installed, you will need to create a free Unity account to start making projects. This will also allow you to sync any projects if you log in to a different machine in the future. It will also provide you with a free license to create games on your machine. If you ever create any games commercially, then you will need a professional license which you can purchase through Unity. Once set up, you will need to click the Install Editor button and select the version of Unity you would like to use. You can see this in Figure 8-1. I would recommend using the version that is recommended by Unity as this will be the most stable and up-to-date version at the time.

A screenshot of the installation of the Unity Editor frame with official release options available for installation. The topmost version, the recommended version, is 2021.3.81 L T S.

Figure 8-1

Unity Hub and Unity software versions

2021.3.8f is my recommended version to use, but do ensure that you select which one has been recommended by Unity to use for this tutorial. Once chosen, you will need to select some modules which will support Unity. As I am running a Mac, in the tutorial, you can see that it has been selected for me to have Visual Studio installed as well. This might not appear for you if you have already got Visual Studio installed on your machine. If you decide to use another code editor, then you can untick Visual Studio to be added. You will need to scroll through the list and choose either Mac Build Support or Windows Build Support, depending on the machine you are using. You are now ready to begin the install!

Once the software has been installed, you can now create a new project. Click the blue button which says New Project. On the left-hand side, choose Core. Then select 2D and give the project a name, such as “Platformer Test Build .” You can see this in Figure 8-2. When you are ready, click Create Project and wait for Unity to open !

A screenshot of the Unity builder with options to create a new 2 D core product.

Figure 8-2

Unity Hub with the selection of templates

Step 1

We’re going to begin with a simple Sprite made within Unity. Right-click in the Project window and select Create ➤ Sprite ➤ Circle. Make sure to name your sprite as “Player” so your assets can be organized appropriately. You can see this method in Figure 8-3.

A screenshot of the Asset viewer with the mouse hovering on the Create a Circle option.

Figure 8-3

Creating a Circle object in the Asset viewer

Drag and drop the Player sprite into your Hierarchy window. This will place the Sprite in the Scene at the coordinates 0, 0, 0 and turn this into a Player object.

Step 2

Now select the Player object that you have just created and, in the Inspector, click Add Component. Search for “playerScript,” click New Script, and click Create and Add. This will not only create the script in our Project, but it will automatically add it to our Player object. You can see this in Figure 8-4.

A screenshot of the Add Component option within the Unity Builder program has the default name as playerScript with a Create and Add button below.

Figure 8-4

Creating a new playerScript script

Double-click the Script in the Inspector which will then open the script in your chosen code editor.

Step 3

Let’s start by having our Player move from side to side. Add the following script into your chosen code editor:
public class playerScript : MonoBehaviour
{
    public float speed;
    void Start()
    {
    }
    void Update
    {
       float h = Input.GetAxisRaw("Horizontal");
       transform.Translate(new Vector3(h * speed * Time.deltaTime, 0, 0));
    }
}

This will allow our player to move across the X axis so the player can move left and right. Using Time.deltaTime ensures a smooth translation. Once completed , be sure to save the script so it can compile within Unity. You can do this by either pressing Ctrl+S or Command+S or clicking File ➤ Save. When you have returned to Unity, you need to look at the Inspector on the right side of the screen and set the Speed float to something greater than zero. You should now be able to run your game and see the player move from left to right!

Step 4

Now as we have our movement set up, we now need to apply an environment for our player to walk around on. To do this, we will create a simple tilemap that the player will be able to walk on and jump on. Start by adding a tilemap into your scene. You can see this in Figure 8-5.

A screenshot of the Game Object tab has the mouse pointer hovering on the Tilemap option within the 2 D object sub-tab.

Figure 8-5

Selecting the Tilemap from the 2D Object menu

Next, open the Tile Palette as shown in Figure 8-6.

A screenshot of the Window tab has the mouse pointer hovering on the Tile Palette option within the 2 D object sub-tab.

Figure 8-6

Opening the Tile Palette from the 2D window

Click Create New Palette, name your Palette “Environment,” and click Create. Save this in the Assets folder of your Unity project, as shown in Figure 8-7 (It will open your file browser window by default). This will appear when you try to save the Environment.

A screenshot of the Tile Palette window has the mouse pointer hovering inside the Name box within the Create New Palette window. Options to change the Grid and Cell size are present below.

Figure 8-7

Tile Palette and creating the Environment palette

Create a new square and call it Ground. (This is the same method we took to create the Circle which is now our player! You can see this in Figure 8-8.) Drag this onto your Tile Palette in the window (this should still be open from when you created your Environment) and save the file as “groundTile” in your Assets folder.

A screenshot of the Asset reviewer tab has the mouse pointer hovering on the Square option within the Create Sprites sub-tab.

Figure 8-8

Creating a Square object in the Asset viewer

Making sure that you have the Brush tool selected in the Tile Palette window (you can see this button third from the left at the top of Figure 8-9), click the white square in the window, and then click and drag in empty to create your platforms.

A screenshot of the assets environment. It is composed of grids. The mouse pointer hovers over the ground asset. The environment editor on the left has the blown up view with the z position set to 0.

Figure 8-9

Creating the ground using the Tile Palette

Step 5

For your final step to making the environment, you need to allow the tilemap to collide with the player. Make sure that you select the Tilemap from the Hierarchy as shown in Figure 8-10.

A screenshot of the Sample scene with the Tile map menu selected from the Grid dropdown function.

Figure 8-10

Selecting the Tilemap object from the Hierarchy

You now need to add a Tilemap Collider 2D from the Inspector as shown in Figure 8-11.

A screenshot of the Tilemap Renderer tab depicts the Sprites default tab below and the add component portion is highlighted with a tile map collider 2 D element chosen from the search menu above.

Figure 8-11

Adding a Tilemap Collider 2D component in the Inspector

Step 6

For the final part of this tutorial, we now need to implement a jump feature for our player. To do this, return to the playerScript and add the following code highlighted in Bold :
public class playerScript : MonoBehaviour
{
    public float speed, jumpForce;
    public Rigidbody2D rb;
    void Start()
    {
       rb = GetComponent<Rigidbody2D>();
    }
    void Update
    {
       float h = Input.GetAxisRaw("Horizontal");
       transform.Translate(new Vector3(h * speed * Time.deltaTime, 0, 0));
       if (Input.GetButtonDown("Jump"))
       {
          rb.AddForce(new Vector2(0, jumpForce), ForceMode2D.Impulse);
       }
    }
}

To get a better understanding of the code we have just added, rb references our RigidBody2D, and AddForce will add a force to any specified direction. We create a Vector2 (X and Y coordinates) just for this statement by writing new Vector2. We leave X as 0, and apply our jumpForce to the Y axis. The last element is identifying the application mode. ForceMode2D.Impulse will apply the force as a singular burst at that moment.

You can now save your script and return to Unity. You now need to add a Rigidbody2D and Collider to our object. This can be done in the Inspector with the Player selected. Click Add Component and search for Rigidbody2D and Collider within the list of components. You will need to select the most appropriate shape for your collider. However, in our case as we are using a circle as our character, you will need to use the Circle Collider.

Step 7

For some of the final steps, we need to create a Ground Check for the player to avoid falling through the ground. While testing your gameplay, you might have noticed that you can jump continuously. This is due to Unity not knowing whether we are allowed to jump or if we are on the ground. This is a mechanic that would fit into games such as Flappy Bird , but as we are making a platformer, we will need to keep it to a single jump.

We need to create an Empty Game Object that will serve as our reference when checking if we have touched the ground. We could use a collision check; however, this would enable our player to wall jump or jump when touching the ceiling as well. By using a Ground Check, we can limit it so jumping is only enabled when the player touches the floor. You can see this in Figure 8-12.

A screenshot of the Game Object menu has the mouse hovering over the Create Empty menu. The keyboard shortcut is Control plus Shift plus N.

Figure 8-12

Creating an empty object from the GameObject menu

With your new object created, give it the name “Ground Check” and make it a child of the Player object by dragging it on top of it in the Hierarchy.

Step 8

We now need to place this new object under our Player in the Scene, so it intersects with the floor whenever we are on the ground. Select the Ground Check object and press the W key to use the Move tool. Drag the object just below the Player. You can use Figure 8-13 as a reference on where the Ground Check needs to go.

A screenshot depicts a circular ground check object in the middle and a circular player object on the left. Both are marked with a pointer. Rectangular objects are present below and to the right.

Figure 8-13

Scene view showing the Ground Check placement

Step 9

We now need to make some changes with our player script to function with our new Ground Check . Open your playerScript and add the following code highlighted in Bold:
public class playerScript : MonoBehaviour
{
    public float speed, jumpForce;
    public Rigidbody2D rb;
    public Transform groundCheck;
    bool grounded = false;
    void Start()
    {
       rb = GetComponent<Rigidbody2D>();
    }
    void Update
    {
       float h = Input.GetAxisRaw("Horizontal");
       grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));
       transform.Translate(new Vector3(h * speed * Time.deltaTime, 0, 0));
       if (Input.GetButtonDown("Jump") && grounded)
       {
           rb.AddForce(new Vector2(0, jumpForce), ForceMode2D.Impulse);
       }
    }
}

This will assign grounded the value of 1 or 0 (true or false) based on the outcome of the line. This line draws a line between our player (transform.position) and the Ground Check object (groundCheck.position). 1 << LayerMask.NameToLayer(“Ground”) ignores all Layers other than Ground. We will create the Ground layer shortly .

Step 10

To bring this tutorial to a close, we need to add a new layer to our tilemap for our Ground Check to work with the environment. Select the Tilemap object in the Hierarchy , and at the top of the Inspector, click the layer drop-down menu and select Add Layer. This is the same method we used for our 3D FPS project earlier in this book. But refer to Figure 8-14 for a recap.

A screenshot of a Tilemap window within the Inspector window. The default layer has a dropdown and the mouse pointer hovers above the Add layer menu.

Figure 8-14

Tilemap in the Inspector to change the Layer type

In the User Layer 8 box, type “Ground” (it will need to be the same spelling as the NameToLayer line in our playerScript which was Ground!). See Figure 8-15.

A screenshot of the Layers menu within the Inspector window, tags and layers portion. The user layer 8, and the Ground menu is chosen.

Figure 8-15

Layer settings in the Inspector to create a new Ground layer

Make sure that you select the tilemap object once more and assign the new layer you have just created as depicted in Figure 8-16.

A screenshot of a Tilemap window within the Inspector window. The default layer has a dropdown and the mouse pointer hovers above the Ground menu.

Figure 8-16

Applying the Ground layer in the Tilemap Inspector

Step 11

For your final step, you will need to assign our Ground Check object to our playerScript. Select the Player object, and drag and drop the Ground Check object from the Hierarchy into the Ground Check field in the Inspector .

You should now be able to test your project and see your player move left to right while also jumping! If you want to expand on your project further, why not try adding some more platforms using the tilemap so your player has something they can jump onto? Or add some mechanics such as double jump or only being able to move in a certain direction? The limit to these tutorials is your imagination!

Conclusion

So far within this chapter, we have covered the following:
  1. 1.

    Developing your skills further within programming and working with the X and Y axes

     
  2. 2.

    Considering directional movement within Unity

     
  3. 3.

    How to create tilemaps

     
  4. 4.

    Working with collisions within 2D

     

With our final practical tutorial completed, we now move into the final chapters of the book which will begin to cover what a HUD and UI mean in terms of game design and how we can create these. This will also branch into menus and accessibility options while also thinking about the most effective ways for your player to use menus during gameplay.

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

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