Menu
CoddyTech

Faster and Faster

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

challenge icon

Challenge

Medium

Make every catch speed up the stars.

  1. Add [SerializeField] private float speedUp = 0.5f;.
  2. In the catch's if, next to score++;, add fallSpeed += speedUp;. Not in ResetStar(): misses call it too.

Press Play and catch a few: each star falls faster. 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;
    private int score;

    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;

        if (Vector3.Distance(transform.position, star.position) < 1f)
        {
            score++;
            Debug.Log("Caught! Score: " + score);
            ResetStar();
        }
        else if (star.position.y < 0f)
        {
            ResetStar();
        }
    }

    void ResetStar()
    {
        star.position = new Vector3(Random.Range(-4f, 4f), 6f, 0f);
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground