Land or Miss
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 85 of 85.
This challenge finishes the tower game, and the course's first section: a crane, a falling block, and a landing test with Mathf.Abs.
Challenge
HardMake each block land on the stack or fall away.
- When the falling block is down to
top's y + 1 and within 1 oftop's x, set its y to exactly that, make ittop, emptyfallingand log"Stack: " + count. - Otherwise, below y =
-3, destroy it, emptyfallingand logMissed!.
Press Play and stack blocks: each landing logs the height. 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;
private float direction = 1f;
private Transform falling;
private int stack;
void Update()
{
transform.position += new Vector3(direction * craneSpeed * Time.deltaTime, 0f, 0f);
if (transform.position.x > craneEdge) direction = -1f;
if (transform.position.x < -craneEdge) direction = 1f;
bool drop = Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0);
if (drop && falling == null)
{
Vector3 spot = new Vector3(transform.position.x, transform.position.y - 1f, 0f);
falling = Instantiate(blockPrefab, spot, Quaternion.identity).transform;
}
if (falling != null)
{
falling.position += Vector3.down * fallSpeed * Time.deltaTime;
// Landing on the stack: the next lesson.
}
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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