Tower Builder
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 67 of 67.
A crane slides back and forth above a base. Each press of Space, or each click, drops a block straight down from the crane. A block that comes down on top of the stack stays there, and the next block has to land on it. A block that misses falls away. The height of the stack is the score.
Write the whole game in one script, Crane, on the crane.
Challenge
HardWrite the Crane script on the Crane. The Inspector sets blockPrefab (the Block prefab), top (the Base, the top of the stack so far), craneSpeed (3), craneEdge (4) and fallSpeed (7).
- The crane slides along x at
craneSpeedunits per second. PastcraneEdgeit turns back left, and past-craneEdgeit turns back right. - Space or a left click drops a Block at the crane's x, 1 unit below the crane. While a block is falling, more presses do nothing.
- The falling block moves down at
fallSpeedunits per second. - When its y gets down to
top's y plus 1, and its x is less than 1 fromtop's x, it lands: set its y to exactlytop's y plus 1, make it the newtop, and log the height of the stack asStack: 1,Stack: 2and so on. - A block that does not land keeps falling. Below y = -3, destroy it and log
Missed!.
Press Play and build a tower, then Check.
Try it yourself
using UnityEngine;
public class Crane : MonoBehaviour
{
[SerializeField] private GameObject blockPrefab;
[SerializeField] private Transform top;
[SerializeField] private float craneSpeed = 3f;
[SerializeField] private float craneEdge = 4f;
[SerializeField] private float fallSpeed = 7f;
void Update()
{
}
}
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