Menu
CoddyTech

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 icon

Challenge

Hard

Make each block land on the stack or fall away.

  1. When the falling block is down to top's y + 1 and within 1 of top's x, set its y to exactly that, make it top, empty falling and log "Stack: " + count.
  2. Otherwise, below y = -3, destroy it, empty falling and log Missed!.

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.
        }
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Scripting Basics

Practice on your own: Unity playground