Unity Tutorial – Movement / Jump in a 2d Scene

  • by

Disclaimer: I am a Unity3d beginner, so my way of doing things might not be the most efficient way. The purpose of this and my future Unity3d tutorials is to document what I have learned and hopefully it will have some value for you as well. Let’s get started!

Content overview

  • Build the scene using Prefabs
  • Apply physics to player (Rigidbody2D)
  • C# script to move / jump with the player
  • Result and Next Steps

Build the Scene using Prefabs

What are prefabs: I understand Prefabs as blueprint for other Game Objects to use. You create one and then use multiple instances of it that have the same properties.

In order to create a prefab all that is needed is to drag a game object in this case a 2d Object -> Sprite -> Cube from the Hierarchy tab into the Project tab.

With that complete you can then drag multiple times the prefab cube from the Project tab into the Scene in order to create the level you like.

Basic scene level build

Since we want the player to land and move on these ground blocks, a final thing needs to be added to the prefab. A Box Collider 2D component that can be found in the Inspector tab of the Cube prefab.

Box Collider 2D added to prefab

Apply physics to player (Rigidbody2D)

For the moment I use a simple 2D Object -> Sprites -> Capsule as the player.

Add a new GameObject Object -> Sprites -> Capsule

In order for the player to be able to stand and move we need to add the following two components within the player (capsule) Inspector tab.

  • Rigidbody2d (In order to add physics so the player can fall)
  • Capsule Collider 2d (in order for the player to detect and stand on the ground)
Rigidbody2D and Capsule Collider2D components added to player.

Now by pressing the start button the capsule should have gravity and fall (due to Rigidbody2d) and stops on the ground (due to box and capsule collider).


C# script to move / jump with the player

Create a new C# script from the player inspector (I called it movement) and open the file in Visual Studio Code.

Move

There are a few ways to move GameObjects around but in this Tutorial I use transform.Translate to move the player.

The code reads as follows:

  • Add a speed field that will allow to change the speed in the editor.
  • Add a custom move method that will capture the left/right arrow key press and moves the player multiplied by speed.
  • Place the move method in the Unity Update method to run every frame.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class movement : MonoBehaviour
{
     public float speed = 10f;
     Rigidbody2D rb;
   
    void Start() 
   {
       rb = GetComponent<Rigidbody2D>();
   }

    void Update()
    {
        move();
    }

    void move() {
         float movement = Input.GetAxis("Horizontal") * Time.deltaTime * speed;
         transform.Translate(movement,0,0);
    }
}

Jump

The next thing to include to the same script is the functionality for the player to jump once the Space Bar is pressed.

The code reads as follows:

  • Create a custom jump method that will move the player up.
  • Add a condition in the Update function that will check if the Space bar is pressed and the player is on the Ground. If so then call the jump method.
  • Add a Unity OnCollisionEnter2d method on the player Object that will check if the player is touching the ground.
  • Set the logic that the player can only jump if on the ground to prevent multiple jumps in the air.
using UnityEngine;
public class movement : MonoBehaviour
{
    public float speed = 10f;
    public float jumpForce = 22f;
    public bool isGrounded;

    Rigidbody2D rb;
   
    void Start() 
   {
       rb = GetComponent<Rigidbody2D>();
   }

    void Update()
    {
         move();

        if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
        {
            jump();
        }
    }

    void move()
    {
        float movement = Input.GetAxis("Horizontal") * Time.deltaTime * speed;
        transform.Translate(movement, 0, 0);
    }

    void jump()
    {
        rb.velocity = Vector2.up * jumpForce;
        isGrounded = false;
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Ground")
        {
            isGrounded = true;
        }
    }
} 

Result and Next Steps

Congratulations to make it that far! If you follow this tutorial then you should be able to create a simple 2d movement in Unity including Jumping!

In the next tutorial I will continue and add camera movement and restriction to prevents the player from exiting the camera window.

Let me know in the comments in case you have questions or suggestions for future Unity tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *