Menu
CoddyTech

Three Lanes

Lesson 1 of 20 in Coddy's Unity Game: Sky Lanes course.

In this course you build one whole game, a feature a lesson. A runner races along a road high in the sky. Barriers, bars and walls come at it, coins line the lanes, and the road gets faster the longer you last.

The project already has four scripts: Runner on the player, Road, GameManager and Coin. Most are empty for now and fill up lesson by lesson. A fifth, CameraFit on the camera, is given: it widens the view on a tall phone screen so all three lanes fit, and you will not need to change it.

The runner never moves forward. It only moves between three lanes: left, middle and right. Keep the lane as a whole number, -1, 0 or 1, and work out where that is on the x axis:

float targetX = lane * laneWidth;

The runner has a CharacterController, so it moves with controller.Move(motion): Move takes how far to go this frame, not where to end up. To land on targetX, move by the difference between it and where the runner is now:

float x = targetX;
Vector3 move = new Vector3(x - transform.position.x, 0f, 0f);
controller.Move(move);

Mathf.Max(-1, lane - 1) is lane - 1, but never less than -1, so there is no lane past the left one.

challenge icon

Challenge

Easy
  1. In Runner.Update, when A or the left arrow is pressed (Input.GetKeyDown), set lane = Mathf.Max(-1, lane - 1).
  2. When D or the right arrow is pressed, set lane = Mathf.Min(1, lane + 1).
  3. Then work out targetX and move the runner there with controller.Move, as above.
  4. Press Play and try A and D.

Try it yourself

using UnityEngine;

public class Runner : MonoBehaviour
{
    public float laneWidth = 2.5f;

    public int lane;

    private CharacterController controller;

    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    void Update()
    {
        // change lanes here
    }
}

All lessons in Unity Game: Sky Lanes

Practice on your own: Unity playground