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
MediumStart Dodge the Blocks: steer the runner along its lane.
- In
Update(), copytransform.positionintoVector3 p, and addInput.GetAxisRaw("Horizontal") * speed * Time.deltaTimetop.x. The raw axis moves at full speed at once. - Set
p.x = Mathf.Clamp(p.x, -laneEdge, laneEdge);, thentransform.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
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