Menu
CoddyTech

Catch It

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 52 of 85.

challenge icon

Challenge

Medium

Catch the star and count the catches.

  1. Add a field private int score;.
  2. After the star moves, when Vector3.Distance(transform.position, star.position) < 1f, add 1 to score and log "Caught! Score: " + score.
  3. In that if, move the star back to y = 6f, keeping its x and z.

Press Play and slide under the star: the Console shows Caught! Score: 1. Then Check.

Try it yourself

using UnityEngine;

public class Catcher : MonoBehaviour
{
    [SerializeField] private float speed = 6f;
    [SerializeField] private Transform star;
    [SerializeField] private float fallSpeed = 3f;

    void Update()
    {
        float x = transform.position.x;
        if (Input.GetKey(KeyCode.RightArrow))
        {
            x += speed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            x -= speed * Time.deltaTime;
        }
        x = Mathf.Clamp(x, -4f, 4f);
        transform.position = new Vector3(x, transform.position.y, transform.position.z);

        star.position += Vector3.down * fallSpeed * Time.deltaTime;
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground