Lesson 2.4 - Collision Decisions
Our game is coming along nicely, but there are are some critical things we must add before it’s finished. First off, instead of pressing S to spawn the animals, we will spawn them on a timer so that they appear every few seconds. Next we will add colliders to all of our prefabs and make it so launching a projectile into an animal will destroy it. Finally, we will display a “Game Over” message if any animals make it past the player.
Make a new method to spawn animals
- In SpawnManager.cs, create a new void SpawnRandomAnimal() {} function beneath Update()
- Cut and paste the code from the if-then statement to the new function
- Call SpawnRandomAnimal(); if S is pressed
Spawn the animals at timed intervals
- In Start(), use InvokeRepeating to spawn the animals based on an interval, then test.
- Remove the if-then statement that tests for S being pressed
- Declare new private startDelay and spawnInterval variables then playtest and tweak variable values
Add collider and trigger components
- Double-click on one of the animal prefabs, then Add Component > Box Collider
- Click Edit Collider, then drag the collider handles to encompass the object
- Check the “Is Trigger” checkbox
- Repeat this process for each of the animals and the projectile
- Add a RigidBody component to the projectile and uncheck “use gravity”
Destroy objects on collision
- Create a new DetectCollisions.cs script, add it to each animal prefab, then open it
- Before the final } add OnTriggerEnter function using autocomplete
- In OnTriggerEnter, put Destroy(gameObject);, then test
- In OnTriggerEnter, put Destroy(other.gameObject);
Trigger a “Game Over” message
- In DestroyOutOfBounds.cs, in the else-if condition that checks if the animals reach the bottom of the screen, add a Game Over messsage: Debug.Log(“Game Over!”)
- Clean up your code with comments
- If using Visual Studio, Click Edit > Advanced > Format document to fix any indentation issues (On a Mac, click Edit > Format > Format Document)