Menu
CoddyTech

Catch It

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 38 of 67.

challenge icon

Challenge

Medium

Catch the star. Add a score that starts at 0. When the star comes closer than 1 unit to the catcher (measure with Vector3.Distance), the star is caught:

  • add 1 to score,
  • log Caught! Score: 1, with the new score,
  • move the star back up to y = 6, keeping its x and z, so it falls again.

A star that misses keeps falling for now. Keep everything from the earlier steps.

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