Menu
CoddyTech

Three Lanes

Part of the Building Real Games section of Coddy's Unity journey. Lesson 27 of 60.

This chapter builds an Endless Runner. A runner races down a road of three lanes and switches lanes to dodge the obstacles that come toward it. Over the next lessons the road speeds up, the distance shows on screen, a crash ends the run with a button to run again, and the best run is saved. The runner never moves forward: it stays at z = 0 and the obstacles travel toward it, so the road never runs out. The game has four scripts, Runner, Spawner, Obstacle and GameManager, and the last three are empty for now.

A runner in lanes is not steered like a car: it is always in one of a few places. Keep the place as a whole number, change the number on a key press, and work out the position from it. This window cleaner's platform serves the five floors of a building, 3 units apart:

[SerializeField] private float floorHeight = 3f;
[SerializeField] private float moveSpeed = 6f;
private int floor = 0;

void Update()
{
    if (Input.GetKeyDown(KeyCode.UpArrow)) floor++;
    if (Input.GetKeyDown(KeyCode.DownArrow)) floor--;
    floor = Mathf.Clamp(floor, 0, 4);

    Vector3 p = transform.position;
    p.y = Mathf.MoveTowards(p.y, floor * floorHeight, moveSpeed * Time.deltaTime);
    transform.position = p;
}

GetKeyDown makes one press one floor, where GetKey would add a floor on every frame the key is held. Mathf.Clamp keeps the number on the building, so up on the top floor does nothing, and the next press down goes straight to floor 3. Mathf.MoveTowards slides the platform toward its floor at moveSpeed units a second and stops exactly on it, instead of jumping there in one frame. The position is a copy, changed and assigned back, because transform.position.y cannot be set on its own.

challenge icon

Challenge

Medium

Make the arrows move the runner between three lanes.

  1. In Runner's Update(), lane-- on Input.GetKeyDown(KeyCode.LeftArrow) and lane++ on the right arrow.
  2. Keep it on the road: lane = Mathf.Clamp(lane, -1, 1);.
  3. Copy transform.position into p, move p.x toward lane * laneWidth with Mathf.MoveTowards at laneSpeed * Time.deltaTime, and assign p back.

Press Play, click the game and switch lanes: the runner slides across. Then Check.

Try it yourself

using UnityEngine;

public class Runner : MonoBehaviour
{
    public float laneWidth = 2.5f;
    public float laneSpeed = 15f;
    private int lane = 0;   // -1 is the left lane, 0 the middle, 1 the right

    void Update()
    {
        // Change lanes with the arrows, then slide toward the lane's x
    }
}

All lessons in Building Real Games

Practice on your own: Unity playground