Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 36 ยท Projects and Practice

Project: Build an Endless Runner in Unity

Build a 3D lane-based endless runner in Unity - lane switching, procedural track chunks, obstacle spawning, rising speed, coins, score and game over - with runnable stand-ins.

An endless runner looks simple: a character runs forward forever and dodges obstacles. Under the hood it teaches a lot: procedural generation, object pooling, difficulty curves, mobile-friendly input and a tidy game state flow. It is also a classic mobile genre, so it is a good portfolio piece.

This lesson describes the full project. Unity is not available on this site, so the MonoBehaviour code is read-only, while the algorithms (lane movement, chunk recycling, spawn rules, speed and score) run as plain C# stand-ins.

Design

  • Three lanes at x = -2, 0, +2. The player switches lane with swipe or A/D, jumps with up and slides with down.
  • The world does not scroll the player forward forever (floating point precision breaks far from the origin). Instead, the world moves toward the player or the player moves and the world recycles chunks ahead of it.
  • The track is built from chunks (prefabs of fixed length, say 30 units) chosen at random and recycled behind the player.
  • Speed rises over time; hitting an obstacle ends the run; coins add score.
flowchart LR
  M["Main Menu"] --> P["Playing"]
  P -->|"hit obstacle"| G["Game Over"]
  G -->|"Retry"| P
  G -->|"Menu"| M
  P -->|"Pause"| Z["Paused"]
  Z -->|"Resume"| P

A small game-state machine controls what the UI and input do.

The player: three lanes

Lane switching is a smooth move toward a target x, not a physics push. Keep a lane index from 0 to 2 and interpolate:

C#
using UnityEngine;

public class RunnerPlayer : MonoBehaviour
{
    [SerializeField] float laneWidth = 2f;
    [SerializeField] float laneChangeSpeed = 14f;
    [SerializeField] float jumpHeight = 2f;
    [SerializeField] float gravity = -30f;
    [SerializeField] CharacterController controller;

    int lane = 1;                 // 0 left, 1 middle, 2 right
    float verticalVelocity;

    public void MoveLeft()  => lane = Mathf.Max(0, lane - 1);
    public void MoveRight() => lane = Mathf.Min(2, lane + 1);

    public void Jump()
    {
        if (controller.isGrounded) verticalVelocity = Mathf.Sqrt(jumpHeight * -2f * gravity);
    }

    void Update()
    {
        float targetX = (lane - 1) * laneWidth;
        float dx = Mathf.MoveTowards(transform.position.x, targetX, laneChangeSpeed * Time.deltaTime) - transform.position.x;

        if (controller.isGrounded && verticalVelocity < 0) verticalVelocity = -2f;
        verticalVelocity += gravity * Time.deltaTime;

        controller.Move(new Vector3(dx, verticalVelocity * Time.deltaTime, GameManager.Speed * Time.deltaTime));
    }
}

The jump formula v = sqrt(h * -2 * g) is the physics identity for reaching height h under gravity g: no tuning of an arbitrary force. Swipe input is a drag delta compared to a threshold: if abs(dx) > abs(dy) it is a horizontal swipe (left or right), otherwise vertical (jump or slide).

C# Stand-in: swipe detection and jump physics

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.

The air time tells you the design limit: at speed 20 units per second a jump of 0.9 s covers 18 units, so obstacles must not be longer than that.

Procedural track chunks

Pre-build 6 to 10 chunk prefabs: empty straight, one low barrier, a wall in two lanes, a row of coins, a ramp. Keep a queue of active chunks. Each frame, if the oldest chunk is far behind the player, move it to the end of the line (reusing it; no Instantiate or Destroy) and give it a new random layout.

C# Stand-in: recycling track chunks

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.

In Unity the Add() step takes a pooled chunk object, repositions it with transform.position = new Vector3(0, 0, frontZ), and enables the right child set (obstacles, coins). To avoid unfair layouts, have each chunk list which lanes are blocked and refuse to stack blocked lane sets that leave no path.

Speed, difficulty and score

Speed should rise quickly at first and then flatten, otherwise the game becomes impossible. A common formula is a smooth curve toward a maximum: speed = max - (max - start) * exp(-k * t). Score is usually distance plus coins times a multiplier.

C# Stand-in: difficulty curve and score

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.

C#
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{
    public enum State { Menu, Playing, Paused, GameOver }
    public static float Speed { get; private set; }
    public static State Current { get; private set; } = State.Menu;

    [SerializeField] float startSpeed = 10f, maxSpeed = 28f, k = 0.03f;
    float runTime;
    public static int Coins, Best;

    public void StartRun()
    {
        runTime = 0; Coins = 0; Current = State.Playing; Time.timeScale = 1f;
    }

    void Update()
    {
        if (Current != State.Playing) { Speed = 0; return; }
        runTime += Time.deltaTime;
        Speed = maxSpeed - (maxSpeed - startSpeed) * Mathf.Exp(-k * runTime);
    }

    public void Die()
    {
        Current = State.GameOver;
        Best = Mathf.Max(Best, Mathf.RoundToInt(runTime * Speed / 10f) + Coins * 5);
        PlayerPrefs.SetInt("best", Best);
    }

    public void Retry() => SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}

Use Time.timeScale = 0 for pause, but remember animations and coroutines using Time.deltaTime freeze; UI animations that should keep running use Unscaled Time.

Obstacles and collisions

Give obstacles a trigger collider and a tag. In the player's OnControllerColliderHit (for a CharacterController) or OnTriggerEnter, call GameManager.Die(). Add a short invincibility window after revival and a near miss bonus: when an obstacle passes within a small distance without a hit, grant bonus score and play a sound. Coins in a sine-wave arc or in a straight lane line encourage movement.

Polish and publishing

A camera that follows with slight lag and lean into lane changes; speed lines (a particle system) that scale with speed; background parallax or a curved-world shader (curves the road down the horizon so spawning is hidden); sound that speeds up with the game; and haptics on mobile. Test the touch controls on a real device, profile it (see Profiler and optimization) and build for Android or iOS (Building and publishing). Monetization such as rewarded "continue" ads or cosmetics is the last step, after the core loop is fun.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why recycle track chunks instead of instantiating new ones?

    Moving an existing chunk to the front costs almost nothing.
  2. 2. Which formula gives the initial jump velocity for height h and gravity g (negative)?

    It follows from v squared = 2 * g * h when the final velocity at the peak is zero.
  3. 3. What does a curve like max - (max - start) * exp(-k * t) do to speed?

    The exponential term shrinks, so speed approaches max smoothly.
  4. 4. How do you detect a horizontal swipe?

    Compare absolute dx and dy, then apply a minimum distance to ignore taps.

Summary

  • Lane-based movement, swipe input and a physics-derived jump are the controller basics.
  • Procedural chunks are recycled from a queue with random but fair layouts.
  • A saturating speed curve and distance plus coin score shape the difficulty.
  • A small game-state machine, polish effects and device testing finish the game.

Next: Practice Exercises and Next Steps