Catch It
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 38 of 67.
Challenge
MediumCatch 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
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon