Hazard Collectible in Unity

2D Space Shooter — Phase II: Core Programming Challenges

Dennisse Pagán Dávila
Level Up Coding

--

Objective: Create a Hazard that slows down the player for a short period of time.

Note: This is part of a retro-style 2D Space Shooter where power-ups can be collected by the player. This Hazard will behave just like a power-up, although collecting it will have adverse effects on the player. As such, this will be following the Power-Up script.

Programming the Hazard

  1. Add global bool variable. This will allow us to toggle the hazard later on.

2. Create a method to handle set the bool value to true when necessary. It’s best practice to create a method to handle bool value changes rather than doing it on the fly. This is also where we slow down the player by halving the speed.

3. Make a coroutine to establish the duration of the hazard. The coroutine below is programmed so that the Player’s speed returns to normal after 5 seconds. The previously created bool variable is set to false so that the program knows it no longer needs to halve the speed.

4. Now that you have a coroutine, it’s time to start it. This will be added to the previously made void method.

5. Call the HazardEnabled method on when the player comes in contact with the hazard. This logic relies on OnTriggerEnter detection. Mine was placed within a Modular Power-Up Script which uses a switch statement to execute methods depending on which object is detected.

The Result:

This article is part of a series of Core Programming Challenges from GameDevHQ. In the next article, I will be writing about implementing an enemy that can use a barrier/shield!

--

--

Software Engineer that specialize in Game Development. Currently looking for new opportunities. LinkedIn: https://rb.gy/xdu8nu