Star After Star
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 39 of 67.
Challenge
MediumSend a new star after every catch and every miss. A star is missed when its y drops below 0. Caught or missed, the star restarts at y = 6 and z = 0, at a random x between -4 and 4. Random.Range(min, max) returns a random float between min and max, so Random.Range(-4f, 4f) picks that x.
Both cases restart the star the same way, so write it once in a method, void ResetStar(), and call it from both. A miss does not score. 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;
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);
star.position = new Vector3(star.position.x, 6f, star.position.z);
}
}
}
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