Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 36 ยท Projects and Practice

Project: Build a 2D Platformer in Unity

Build a complete 2D platformer in Unity step by step - scene setup, tilemap level, character controller with coyote time and jump buffering, coins, enemies, checkpoints and a UI.

In this project you build a small but complete 2D platformer: a hero who runs and jumps across a tilemap level, collects coins, avoids patrolling enemies, respawns at checkpoints and reaches a goal flag. It uses nearly everything from this chapter: UI, input, animation, audio and the 2D workflow.

Unity is not available on this site, so every step is described and the C# MonoBehaviours are read-only. The part that makes a platformer feel good, the jump logic, is also available as a runnable plain C# stand-in so you can tune the numbers and see the result as text.

The plan

Step What you build
1 Project and scene setup
2 Level with Tilemap and colliders
3 Player controller (move, jump, coyote time, jump buffer)
4 Collectibles and score UI
5 Patrolling enemies and damage
6 Checkpoints, respawn and win condition
7 Animation and sound

1. Project setup

Create a new project from the Universal 2D template. Import your sprites at one Pixels Per Unit (16 or 32), point filter, no compression (see Sprites and tilemaps). Create Sorting Layers: Background, Ground, Characters, Foreground. Install the Input System and Cinemachine packages. Set the Main Camera to orthographic and add a CinemachineCamera following the player later.

Create layers Ground, Player, Enemy and Hazard, and in the Physics 2D Layer Collision Matrix disable Player vs Player and Enemy vs Enemy.

2. The level

Create GameObject > 2D Object > Tilemap > Rectangular. Paint ground and platforms from a Tile Palette. On the Tilemap add Tilemap Collider 2D, tick Composite Operation > Merge, then add Composite Collider 2D (it adds a Rigidbody2D: set Body Type: Static). Put the tilemap on the Ground layer. Make a second tilemap for decoration without colliders. Use a thin trigger collider along the bottom of the level, tagged Hazard, as a "fell off the world" zone.

3. The player controller

Create the hero: a sprite with Rigidbody2D (Dynamic, Freeze Rotation Z, interpolation on), a CapsuleCollider2D and a small empty child GroundCheck at the feet. A good platformer jump is built from four rules:

  1. Variable jump height: release the button early to cut the jump short.
  2. Coyote time: allow a jump for ~0.1 s after walking off a ledge.
  3. Jump buffer: remember a jump press for ~0.1 s before landing, so a slightly early press still works.
  4. Heavier gravity when falling so the jump feels snappy, not floaty.
C#
using UnityEngine;
using UnityEngine.InputSystem;

[RequireComponent(typeof(Rigidbody2D))]
public class PlayerController : MonoBehaviour
{
    [Header("Movement")]
    [SerializeField] float moveSpeed = 8f;
    [SerializeField] float acceleration = 60f;
    [Header("Jump")]
    [SerializeField] float jumpVelocity = 14f;
    [SerializeField] float coyoteTime = 0.1f;
    [SerializeField] float jumpBuffer = 0.1f;
    [SerializeField] float fallGravityScale = 3f;
    [SerializeField] float cutGravityScale = 6f;
    [Header("Ground check")]
    [SerializeField] Transform groundCheck;
    [SerializeField] LayerMask groundMask;
    [SerializeField] InputActionReference moveAction, jumpAction;

    Rigidbody2D rb;
    float coyoteCounter, bufferCounter, baseGravity;
    bool jumpHeld;

    void Awake() { rb = GetComponent<Rigidbody2D>(); baseGravity = rb.gravityScale; }
    void OnEnable()  { moveAction.action.Enable(); jumpAction.action.Enable(); }
    void OnDisable() { moveAction.action.Disable(); jumpAction.action.Disable(); }

    bool IsGrounded() => Physics2D.OverlapCircle(groundCheck.position, 0.12f, groundMask);

    void Update()
    {
        if (IsGrounded()) coyoteCounter = coyoteTime; else coyoteCounter -= Time.deltaTime;

        if (jumpAction.action.WasPressedThisFrame()) bufferCounter = jumpBuffer;
        else bufferCounter -= Time.deltaTime;

        jumpHeld = jumpAction.action.IsPressed();

        if (bufferCounter > 0f && coyoteCounter > 0f)
        {
            rb.linearVelocity = new Vector2(rb.linearVelocity.x, jumpVelocity);
            bufferCounter = coyoteCounter = 0f;
        }
    }

    void FixedUpdate()
    {
        float target = moveAction.action.ReadValue<Vector2>().x * moveSpeed;
        float vx = Mathf.MoveTowards(rb.linearVelocity.x, target, acceleration * Time.fixedDeltaTime);
        rb.linearVelocity = new Vector2(vx, rb.linearVelocity.y);

        bool rising = rb.linearVelocity.y > 0f;
        rb.gravityScale = !rising ? fallGravityScale
                         : !jumpHeld ? cutGravityScale        // released early: cut the jump
                         : baseGravity;
    }
}

Flip the sprite with spriteRenderer.flipX = vx < 0. Add a Cinemachine Position Composer with a small dead zone and a Confiner 2D bound to the level, as described in Timeline and Cinemachine.

Tune the jump with numbers

You can reason about a jump before touching the editor. With initial velocity v, gravity g and a gravity multiplier, the height is roughly v^2 / (2 * g * scale). This stand-in simulates the controller's jump logic frame by frame (coyote time, buffer, early release) so you can check heights and timing.

C# Stand-in: platformer jump logic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

A short tap reaches a lower peak than a held press, which is the variable jump height. The last line shows why coyote time makes the game feel fair: the press came 0.083 s after leaving the ledge and still counted.

4. Coins and score

A coin is a sprite with a CircleCollider2D (Is Trigger), an animation (spinning sprite sheet) and a script. A static GameEvents class or a ScriptableObject event channel keeps UI decoupled:

C#
using System;
using UnityEngine;

public static class GameEvents
{
    public static event Action<int> CoinsChanged;
    public static event Action PlayerDied;
    public static event Action LevelCompleted;
    public static void RaiseCoins(int total) => CoinsChanged?.Invoke(total);
    public static void RaiseDied() => PlayerDied?.Invoke();
    public static void RaiseCompleted() => LevelCompleted?.Invoke();
}

public class Coin : MonoBehaviour
{
    [SerializeField] AudioClip pickup;
    void OnTriggerEnter2D(Collider2D other)
    {
        if (!other.CompareTag("Player")) return;
        other.GetComponent<PlayerStats>().AddCoin();
        AudioSource.PlayClipAtPoint(pickup, transform.position);
        Destroy(gameObject);
    }
}

public class PlayerStats : MonoBehaviour
{
    int coins;
    public void AddCoin() { coins++; GameEvents.RaiseCoins(coins); }
}

A HUD script subscribes in OnEnable and updates a TextMeshPro label (Buttons, text and UI events).

5. Enemies

A patrolling enemy walks between two points and turns at walls or ledges. Stomping from above defeats it; touching it from the side hurts the player. Decide by comparing positions in OnCollisionEnter2D: if the contact normal points mostly upward, the player landed on top.

C#
using UnityEngine;

public class PatrolEnemy : MonoBehaviour
{
    [SerializeField] float speed = 2f;
    [SerializeField] Transform leftPoint, rightPoint;
    int direction = 1;

    void FixedUpdate()
    {
        transform.Translate(Vector2.right * (direction * speed * Time.fixedDeltaTime));
        if (transform.position.x > rightPoint.position.x) direction = -1;
        if (transform.position.x < leftPoint.position.x) direction = 1;
    }

    void OnCollisionEnter2D(Collision2D hit)
    {
        if (!hit.collider.CompareTag("Player")) return;
        bool stomp = hit.GetContact(0).normal.y < -0.5f;   // normal points from the enemy toward the player's contact
        if (stomp)
        {
            hit.rigidbody.linearVelocity = new Vector2(hit.rigidbody.linearVelocity.x, 10f);  // bounce
            Destroy(gameObject);
        }
        else GameEvents.RaiseDied();
    }
}

6. Checkpoints and the win condition

Keep a Vector2 respawnPoint. Each checkpoint is a trigger that updates it. When PlayerDied fires, wait a moment (coroutine), reset velocity and set the position to respawnPoint. The goal flag triggers LevelCompleted, which shows a UI panel with the coin count and a "Next level" button calling SceneManager.LoadScene. Save the best coin count with the save system from Building and publishing.

C# Stand-in: checkpoint and lives logic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

7. Polish

Add an Animator with Idle, Run, Jump and Fall states driven by Mathf.Abs(velocity.x), velocity.y and the grounded bool (Animator controller). Play sounds for jump, coin and death through an AudioMixer group (Audio). Add particles for landing dust, a screen shake impulse on death and a pause menu with the UI action map.

Extension ideas

Moving platforms (a kinematic Rigidbody2D that carries the player by parenting on contact), wall jump, a dash with cooldown, a boss, a timer and leaderboards, multiple levels loaded from a list and a level-select screen.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is coyote time in a platformer?

    It forgives slightly late jump presses and makes controls feel fair.
  2. 2. How do you get a variable jump height?

    Applying more gravity once the button is released cuts the upward motion short.
  3. 3. Why use a Composite Collider 2D on the tilemap?

    Merged outlines are cheaper and remove tiny gaps where characters could catch.
  4. 4. Why send coin events through GameEvents rather than having Coin reference the HUD?

    Publishers and subscribers do not need direct references to each other.

Summary

  • Set up a Universal 2D project, one PPU, layers and a merged tilemap collider.
  • Great jumps come from variable height, coyote time, a jump buffer and extra fall gravity.
  • Coins, enemies and checkpoints are triggers and collisions plus a small event layer.
  • Animation, audio, camera and UI turn the prototype into a game; extend with new mechanics.

Next: Project: A Top-Down Shooter