Getting bored with your game? Moving and shooting doesn’t entertain like it used to? Just like a much-needed cup of coffee on Monday morning, fire up your game experience with a Power Up!
Objective: Add a collectible power-up object that changes player functionality
- Build Power Up functionality on the Player
- Create a Power Up object with Collision logic
- Add power up to Spawn Manager
Build Power Up Functionality on the Player
A power up can be anything that adds or changes any functionality on your Player for a limited amount of time or a limited number of uses. How your power up functions will be unique to your game and can include anything, such as increasing physical size, defensive stats or fire rate. For the purposes of this article, the power up will just be a flag on the player that turns off after 2 seconds.
You’ll want the power up functionality to be contained in a public method so that the power up can turn on this functionality in the player when collected. To turn off the power up functionality after 2 seconds, use a coroutine.
Create a Power Up object with Collision logic
If you have an asset available for your power up, drag that into the Hierarchy to create a new object. To support collisions with the Player, add a Collider component and check Is Trigger as well as add a Rigidbody component with Gravity Scale set to zero, using the 2D versions if working with a sprite.
Then, add a new script to your power up object and include a OnTriggerEnter(2D) method to check for collisions with the Player. If the power up collides with the Player, activate the power up method on the Player and destroy the Power Up object.
In the Update() method, use Transform.Translate() to move the Power Up down screen. Check if the object has passed the lower screen boundary and destroy it if so.
Once all changes are made to the Power Up object in the Inspector, add it to the Prefabs folder and remove it from the Scene view.
Add power up to Spawn Manager
Finally, in your Spawn Manager script, add a new coroutine to handle spawning the Power Up object at random intervals.
You’ll need a reference to the Power Up prefab to instantiate it, so create a variable and serialize it to assign the prefab from the Inspector. Next, create a new coroutine method. To randomize the time between powerups, you can pass in a Random.Range for WaitForSeconds() and a different value will be used for each iteration of the While() loop. Be sure to instantiate your power up prefab within your loop and start your coroutine in the Start() method.
With the final piece in place, you now have a fully functional power up prototype. You can replace the Power Up flag functionality with anything to improve your gameplay experience. For example, a triple-shot power up:
Because more lasers is always more fun.