Hit!
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 63 of 67.
Challenge
MediumTime for the danger. Keep everything from the earlier steps, and end the game when a block touches the runner:
- Both are cubes 1 unit wide, so a block touches the runner when their x positions are less than 1 apart and their y positions are less than 1 apart.
- Check every block after it moves, every frame. On a touch, log
Game overand turn the script off withenabled = false, so the runner, the blocks and the spawning all stop.
Press Play and see how long you last, 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 = 0f;
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
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