Menu
CoddyTech

The Runner

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 60 of 67.

This chapter builds a small game, Dodge the Blocks. You steer a runner along a lane while blocks fall from the sky, and one touch ends the run. The whole game is one script, Runner, which gains a feature in every lesson: steering, falling blocks, cleaning them up, the hit, and a score.

The first feature is steering that stays on the lane, with Mathf.Clamp(value, min, max) from Catch the Star: it returns min when the value is below the range, max when it is above, and the value itself otherwise. Where the clamp goes matters. This charge meter fills while Space is held, drains when it is not, and never leaves 0 to 10:

[SerializeField] private float charge = 0f;

void Update()
{
    if (Input.GetKey(KeyCode.Space))
    {
        charge += 4f * Time.deltaTime;
    }
    else
    {
        charge -= 2f * Time.deltaTime;
    }
    charge = Mathf.Clamp(charge, 0f, 10f);
    transform.localScale = new Vector3(0.5f, charge, 0.5f);
}

The clamp comes after the change. Clamped first, the value could end the frame one step past the limit, and the bar would be drawn from that value. Mathf.Clamp also returns a new number instead of changing the variable you pass in, so assign the result back.

challenge icon

Challenge

Medium

Start Dodge the Blocks with the runner. The Inspector gives the Runner script speed (6) and laneEdge (4).

  • The left and right arrows move the runner along x at speed units per second.
  • Its x never goes below -laneEdge or above laneEdge, so it stays on the lane.

Press Play, click the game and run to both ends of the lane, then Check.

Try it yourself

using UnityEngine;

public class Runner : MonoBehaviour
{
    [SerializeField] private float speed = 6f;
    [SerializeField] private float laneEdge = 4f;

    void Update()
    {
        // move along x with the arrows, then keep x on the lane
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Scripting Basics