Attracting Powerups with a Magnet
Objective: allow the player to attract all powerups to them by pressing a button.
First we will need to setup a new input button called Magnet that we can use from both the keyboard (the ‘c’ key) and a controller (the right bumper)
We’ll also need to tag each of the powerup prefabs as “Powerup” so our code will be able to tell which game objects to attract to the player.
Now lets starting coding in the Player class. First we add a new if statement to Player.Update that checks if the magnet button is pressed and if the magnet is available to be used.
This calls the PowerupMagnetRoutine which determines if there are powerups on the screen. If there are, it will “magnetize” all of them which will cause them to move toward the player. Then we wait until we’ve collected all the magnetized powerups.
Powerups that are magnetized have a transform variable set to the player’s transform. Then, in their Update method, if that transform is available, it will move toward the player instead of doing their usual leftward drift.
The Player class can figure out when we’ve collected a powerup by creating a new public method in Player that controls the effects of different powerups. Before, this switch statement was in the Powerup class, but by putting it in the Player class, the player can now keep track of how many powerups he has collected during the use of the magnet.
Finally, once the player has collected all the powerups, we start the MagnetCooldownRoutine. This waits until the elapsed time has passed the magnet cooldown time, then allows the player to use the magnet again. We also constantly update the UI during this time.
Finally, the UIManager class needs some new methods. When OnMagnetUsed is called, it sets the UI text to a new string “Magnetizing!” and starts a coroutine. MagnetFlashingRoutine causes a UI gauge to change back and forth between two colors.
Then when UpdateMagnetRecharge is called, it fills up the gauge by setting it’s value to progress, which Player passes in as a number between 0 and 1. The text is set to “Recharging” or “Magnet” depending on whether or not the gauge is full.
Another feature complete! Now the player has the option to grab powerups that are just out of reach.