Hit!
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 79 of 85.
Challenge
MediumEnd the game when a block touches the runner.
- In the block loop, after a block moves, read its position as
Vector3 b. - When
Mathf.Abs(b.x - transform.position.x) < 1f && Mathf.Abs(b.y - transform.position.y) < 1f, logGame over, setenabled = false;andreturn;.
Press Play and let a block land on you: the Console shows Game over and everything stops. Then Check.
Try it yourself
using System.Collections.Generic;
using UnityEngine;
public class Runner : MonoBehaviour
{
[SerializeField] private float speed = 6f;
[SerializeField] private float laneEdge = 4f;
[SerializeField] private GameObject blockPrefab;
[SerializeField] private float spawnEvery = 1f;
[SerializeField] private float fallSpeed = 5f;
private List<GameObject> blocks = new List<GameObject>();
private float timer;
void Update()
{
Vector3 p = transform.position;
p.x += Input.GetAxisRaw("Horizontal") * speed * Time.deltaTime;
p.x = Mathf.Clamp(p.x, -laneEdge, laneEdge);
transform.position = p;
timer += Time.deltaTime;
if (timer >= spawnEvery)
{
timer -= spawnEvery;
Vector3 spot = new Vector3(Random.Range(-laneEdge, laneEdge), 10f, 0f);
blocks.Add(Instantiate(blockPrefab, spot, Quaternion.identity));
}
for (int i = blocks.Count - 1; i >= 0; i--)
{
blocks[i].transform.position += Vector3.down * fallSpeed * Time.deltaTime;
if (blocks[i].transform.position.y < -1f)
{
Destroy(blocks[i]);
blocks.RemoveAt(i);
}
}
}
}
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