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
MediumGive the catcher, the blue bar, its movement.
- In
Update(), copytransform.position.xintofloat x, then add or take awayspeed * Time.deltaTimefor the arrow held. - Keep the 2 unit wide catcher on the floor (x from -5 to 5):
x = Mathf.Clamp(x, -4f, 4f);. - Write
xback intotransform.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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground