Menu
CoddyTech

The Catcher

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

This chapter builds a small game, Catch the Star, one feature per lesson: a star falls, you slide a catcher left and right under it, every catch scores and makes the next star fall faster, and three misses end the game. All of it is one script, Catcher, on the catcher. The first feature is movement: the catcher slides with the arrow keys and never leaves the floor.

Keeping a number inside limits is the job of Mathf.Clamp(value, min, max). It returns min when the value is below min, max when it is above max, and the value itself otherwise. This camera follows the player up a tower, but its height stays between 2 and 12:

[SerializeField] private Transform player;

void Update()
{
    float y = Mathf.Clamp(player.position.y, 2f, 12f);
    transform.position = new Vector3(transform.position.x, y, transform.position.z);
}

Clamp returns a new number and changes nothing by itself, so assign the result. Clamp after all of the frame's changes and before you write the position back, and no frame ever shows the object past its limit.

challenge icon

Challenge

Medium

Give the catcher, the blue bar, its movement.

  1. In Update(), copy transform.position.x into float x, then add or take away speed * Time.deltaTime for the arrow held.
  2. Keep the 2 unit wide catcher on the floor (x from -5 to 5): x = Mathf.Clamp(x, -4f, 4f);.
  3. Write x back into transform.position, keeping y and z.

Press Play and hold the arrows: it stops at the edges. Then Check.

Try it yourself

using UnityEngine;

public class Catcher : MonoBehaviour
{
    [SerializeField] private float speed = 6f;

    void Update()
    {
        // Arrows: slide along x at speed units per second.
        // Keep the whole catcher on the floor (x from -5 to 5, the catcher is 2 wide).
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground