Catch It
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 52 of 85.
Challenge
MediumCatch the star and count the catches.
- Add a field
private int score;. - After the star moves, when
Vector3.Distance(transform.position, star.position) < 1f, add 1 toscoreand log"Caught! Score: " + score. - In that if, move the star back to y =
6f, keeping its x and z.
Press Play and slide under the star: the Console shows Caught! Score: 1. 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;
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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground