Menu
CoddyTech

A Falling Star

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

challenge icon

Challenge

Medium

Make the star fall.

  1. Add [SerializeField] private Transform star; and [SerializeField] private float fallSpeed = 3f; to Catcher. The scene puts the Star in star.
  2. At the end of Update(), add Vector3.down * fallSpeed * Time.deltaTime to star.position, not to the catcher's.

Press Play: the star falls past the catcher and keeps going. Then Check.

Try it yourself

using UnityEngine;

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

    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);
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground