Menu
CoddyTech

The Runner

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 75 of 85.

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: steer the runner along its lane.

  1. In Update(), copy transform.position into Vector3 p, and add Input.GetAxisRaw("Horizontal") * speed * Time.deltaTime to p.x. The raw axis moves at full speed at once.
  2. Set p.x = Mathf.Clamp(p.x, -laneEdge, laneEdge);, then transform.position = p;.

Press Play, click the game and run to both ends: the runner stops at the edges. 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
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground