The Catcher
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 36 of 67.
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
MediumGive the catcher (the blue bar) its movement. While the right arrow is held it slides right (along +x), while the left arrow is held it slides left, both at speed units per second. Its y and z never change.
The floor runs from x = -5 to x = 5 and the catcher is 2 units wide. Clamp its x so the whole catcher always stays on the floor.
Press Play, click the game and try the arrows, 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).
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unity Scripting Basics
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon