Skip to content

Unity Tutorial – Basic 2D Platform Game (Part2)

  • by
Unity Tutorial - Part2 Title image

Disclaimer: I am a Unity3d beginner, so my way of doing things might not be the most efficient way. The purpose of this and 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!

Please be sure you have read the previous Tutorial Part1 before this one.

2D PLAtform Game Tutorial overview

  • Expand the game scene with prefabs
  • Camera follow C# script
  • Update Player C# script to Clamp movement
  • Next steps
  • Unity references

Expand the Game Scene

To keep it simple I just duplicated a few of the (prefab) squares we already used in the first part and placed them around the scene. I encourage you to build your own little scene with e.g. different shapes and colours.

Basic game scene using squares

Camera Follow C# Script

Select the Main Camera in the Hierarchy Window and add a new C# script under Add Component (I called it CameraFollow).

The code reads as follows:

  • Add a Serialised to choose the game object to be followed (the Player).
  • Add Serialised fields adjust the camera limit values in the editor
  • Use the transform.position method of the camera and assign it to the position of the player.
  • Move the camera a bit up and to the front (x and y values) and add distance (z value).
  • Use the Mathf.Clamp method to restrict the view of the camera movement
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
    [SerializeField] Transform player;
    [SerializeField] int leftLimit = 6;
    [SerializeField] int rightLimit = 14;
    [SerializeField] int topLimit = 15;
    [SerializeField] int bottomLimit;
    void LateUpdate()
    {
        transform.position = player.transform.position + new Vector3(2, 1, -10);
        transform.position = new Vector3
            (
                Mathf.Clamp(transform.position.x, leftLimit, rightLimit),
                Mathf.Clamp(transform.position.y, bottomLimit, topLimit),
                transform.position.z
            );
    }
}

In the Inspector of the Main Camera you should see a new field called “Player” under the script component. Press the little dot next to it and select the Player GameObject.

If you press the Play Button the Camera should now follow the Player.

Update Player C# Script

The Problem we still have is that event though the camera stops at our set boundaries, the player movement has no boundaries yet.

In order to correct this we need to change the code of the player script a little. Open the C# Player script and make the following changes to the move() method.

The code reads as follows:

  • Add a new Vector3 variable called pos to store the clamp data
  • Restrict the range for the x position using the Mathf.Clamp method
  • Apply the restricted movement range to the player.
using UnityEngine;
public class PlayerControl : MonoBehaviour
{
    [SerializeField] int speed = 10;
    [SerializeField] int jumpForce = 15;
    [SerializeField] float xMin = -2.0f;
    [SerializeField] float xMax = 22f;
    public bool isGrounded;
    Rigidbody2D rb;
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }
    void Update()
    {
        move();
        if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
        {
            jump();
        }
    }
    void move()
    {
        float horizontalMove = Input.GetAxis("Horizontal") * Time.deltaTime * speed;
        transform.Translate(horizontalMove, 0, 0);
        //Restrict movement with Mathf.Clamp
        Vector3 pos = transform.position;
        pos.x = Mathf.Clamp(transform.position.x, xMin, xMax);
        transform.position = pos;
    }
    void jump()
    {
        rb.velocity = Vector2.up * jumpForce;
        isGrounded = false;
    }
    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Ground")
        {
            isGrounded = true;
        }
    }
}

Next Steps

Well done! If you followed the steps so far you enhanced the game with adding camera movement and player move restrictions.

In the next tutorial I will add coins to the scene for the player to collect. Stay tuned!

Unity References

Links to the Unity documentation for the classes and methods I use in this tutorial.

Leave a Reply

Your email address will not be published.