Lesson 2.2 - Food Flight
In this lesson, you will allow the player to launch the projectile through the scene. First you will write a new script to send the projectile forwards. Next you will store the projectile along with all of its scripts and properties using an important new concept in Unity called Prefabs. The player will be able to launch the projectile prefab with a tap of the spacebar. Finally, you will add boundaries to the scene, removing any objects that leave the screen.
Make the projectile fly forwards
- Create a new “MoveForward” script, attach it to the food object, then open it
- Declare a new public float speed variable;
- In Update(), add transform.Translate(Vector3.forward * Time.deltaTime * speed);, then save
- In the Inspector, set the projectile’s speed variable, then test
Make the projectile into a prefab
- Create a new “Prefabs” folder, drag your food into it, and choose Original Prefab
- In PlayerController.cs, declare a new public GameObject projectilePrefab; variable
- Select the Player in the hierarchy, then drag the object from your Prefabs folder onto the new Projectile Prefab box in the inspector
- Try dragging the projectile into the scene at runtime to make sure they fly
Test for spacebar press
- In PlayerController.cs, in Update(), add an if-statement checking for a spacebar press: if (Input.GetKeyDown(KeyCode.Space)) {
- Inside the if-statement, add a comment saying that you should // Launch a projectile from the player
- Inside the if-statement, use the Instantiate method to spawn a projectile at the player’s location with the prefab’s rotation
Make animals into prefabs
- Rotate all animals on the Y axis by 180 degrees to face down
- Select all three animals in the hierarchy and Add Component > Move Forward
- Edit their speed values and test to see how it looks
- Drag all three animals into the Prefabs folder, choosing “Original Prefab”
- Test by dragging prefabs into scene view during gameplay
Destroy projectiles offscreen
- Create “DestroyOutOfBounds” script and apply it to the projectile
- Add a new private float topBound variable and initialize it = 30;
- Write code to destroy if out of top bounds if (transform.position.z > topBound) { Destroy(gameObject); }
- In the Inspector Overrides drop-down, click Apply all to apply it to prefab
Destroy animals offscreen
- Create else-if statement to check if objects are beneath lowerBound: else if (transform.position.z < lowerBound)
- Apply the script to all of the animals, then Override the prefabs