2d-character-controller

Creating a 2D Character Controller from Scratch in Unity: A Step-by-Step Guide for Beginners

Introduction:

A 2D character controller is the core game mechanic in many platformer and side-scrollers. Movement, jumping, and player interaction with the game world are controlled by it. For someone with no experience in Unity, it would be possible for you to absorb the fundamentals of game physics and input handling in understanding how a character controller is made from scratch.

Here we will not fling the code at you, but explain everything step by step to each and every concept, in an easy-to-understand manner for beginners. At the end, you will have the smooth responsive 2D character moving, jumping, and interacting with the environment – the bare minimum skills for making your very first platformer .

Set Up Your Scene in Unity

New 2D Project:

  • Open Unity and click on “New Project.” Now select the template that’s 2D and give it a meaningful name like “2D Character Controller.” Click Create.

Create Your Player Object:

  • Let’s create a simple player object. First, click on Hierarchy and right-click, go to Create Empty, and name it “Player.”
  • Add a Sprite Renderer by clicking on Add Component and assigning a sprite; it can be a simple square or character image.
  • Let’s add a Rigidbody2D to make the object interact with physics, such as gravity and momentum. Unity applies forces on objects with Rigidbody components so that they move about naturally according to the laws of physics.
  • Finally, let’s add a BoxCollider2D to your player. This allows Unity to detect any collision between the player and other objects, such as the ground.

Create the Ground:

  • Now, let’s create a simple ground for your player to walk on. Right-click in the Hierarchy, go to 2D Object > Sprite, and choose a plain Rectangle.
  • Scale it up with your Rect Tool and put it all the way to the bottom of the screen.
  • Just like for the player, add a BoxCollider2D so Unity knows it’s solid ground. For better results, add also a Rigidbody2D but set it to Static so it doesn’t fall under gravity.

Now our scene should be all set up. You should see a player that is a small object and a ground rectangle beneath it. Alright, the more exciting part now: coding the character controller.

Understanding the Basics of Movement

Movement is probably one of the most basic mechanics in any game. A 2D character will most likely have to worry about movement left/right and jumping. But how does Unity know what we mean when the player presses the left arrow?

Input Handling:

  • The input handling for Unity has built-in functions so we’ll know which buttons a player is pressing. So, for left to right, we use Input.GetAxis(“Horizontal”), which gives a float value between -1 and 1 relative to whether the left or right arrow key is pressed.

Let’s break this process down before we start with code now.

Writing the Character Controller Script

Now that we have the basics under our belts, it’s time to write a script for how we want our player to move. We’ll implement left/right first, then add in jumping and try to smooth out the general movement feel.

Create a Script:

Right click in the project window -> Create -> C# Script, name it PlayerMovement. Attach this script to your Player object by dragging it onto the Player in the Inspector.

Interpretation of Code (Part 1):

Let’s run through brief code for simple left-right movement before we go all the way to complete script.

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    private Rigidbody2D rb;  // We'll use Rigidbody2D for physics
    public float moveSpeed = 5f;  // Variable to control how fast the player moves

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();  // Get the Rigidbody2D component from the player
    }

    void Update()
    {
        Move();  // Call the movement function every frame
    }

    void Move()
    {
        float moveInput = Input.GetAxis("Horizontal");  // Detect if player is pressing left/right
        rb.velocity = new Vector2(moveInput * moveSpeed, rb.velocity.y);  // Apply movement
    }
}

What’s happening here?

  • Accessing the Rigidbody2D component attached to the player so we can control its physics.
  • Move function checks for player input using Input.GetAxis(“Horizontal”). This will give us a value between -1 (left) and 1 (right).
  • Then we use rb.velocity = new Vector2(.), controlling the player’s horizontal movement speed while keeping the y-velocity unchanged for now.

Adding Jumping

Jumping is a primary function in many 2D games. In order for our character to jump, we must apply an upward force along the Y axis upon the player’s jump.

2d Jump

Jump Mechanics:

  • Input.GetKeyDown(“Jump”): This returns when the player jumps. The default seems to be using the space bar.
  • Ground Check: Of course, we want our player to only jump while standing on the ground.

Lets talk how this works before we write it.

Jumping Code and Explanation:

public float jumpForce = 10f;
private bool isGrounded;  // To check if the player is on the ground

void Update()
{
    Move();
    Jump();
}

void Jump()
{
    if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
    {
        rb.velocity = new Vector2(rb.velocity.x, jumpForce);  // Apply a force upwards when jumping
    }
}

// We use collision detection to check if the player is on the ground
private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("Ground"))
    {
        isGrounded = true;  // Player can jump again
    }
}

private void OnCollisionExit2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("Ground"))
    {
        isGrounded = false;  // Player is no longer on the ground
    }
}

What’s happening here?

  • Jump: We are checking if the spacebar is being pressed and if the player has a grounded state, we apply an upward force through Rigidbody’s velocity
  • Ground Check: The OnCollisionEnter2D and OnCollisionExit2D functions allow us to understand when is he touching the ground so that we can only jump at these moments.

Smoothing of the Movement

Now your character will walk and jump but walking stiff. So it’s the time to take it up a notch. We are going to use Mathf.Lerp and ensure that in a game, the player would accelerate and decelerate.

Acceleration and Deceleration

  • Lerp (Linear Interpolation): We add Mathf.Lerp as an effect and make the player smoothly pass over between two values: its current speed and desired speed to move.

Here is how you can make it smooth:

public float acceleration = 2f;
public float deceleration = 2f;
private float currentSpeed = 0f;

void Move()
{
    float moveInput = Input.GetAxis("Horizontal");

    if (moveInput != 0)
    {
        currentSpeed = Mathf.Lerp(currentSpeed, moveSpeed * moveInput, acceleration * Time.deltaTime);
    }
    else
    {
        currentSpeed = Mathf.Lerp(currentSpeed, 0, deceleration * Time.deltaTime);
    }

    rb.velocity = new Vector2(currentSpeed, rb.velocity.y);
}

Conclusion

By the end of this, you would have learned how to create a 2D Character Controller from scratch in Unity, accompanied by many explanations that help you to not only understand what you are writing but also why things work the way they do. Now, with smooth movement, jumping mechanics, and control over accelerations, you’re ready to build on top of this with your creative ideas-dubbed double jumps or wall jumps.

This is truly the beginning of your adventure. Go ahead, try and extend what you learned here. The sky (or perhaps, the platform?) is the limit!

Leave a Reply

Shopping cart

0
image/svg+xml

No products in the cart.

Continue Shopping