Space Shooter Challenge: Powerup Collection
Today’s challenge was to create functionality so that when the ‘C’ Key is pressed, powerups move towards the player. To do so, I would disguise this feature as a Magnet ability that would work on a cooldown state similar to the Thrusters.
In my Player Script, I ran a MagnetCheck method from the Update method. Here, I could check for Input, then run some Coroutines. Additionally, I only wanted to run this if I had a magnet charge greater than 0. My MagnetOff Coroutine starts the cooldown and recharge, so if I press ‘C’ again, I want to stop this. Then I can run my MagnetOn Coroutine which will deal with draining the magnet charge level.
Lets first look at the functionality of the MagnetOn Coroutine. First I need to set a bool, which will come into use for the recharging.
I already have an empty game object that holds all of the spawned Powerups, so I created a reference to this in my Player Script and used GetComponentsInChildren to populate an Array. Then I could run a while loop that returns true when the magnet level is greater than 0, and when the ‘C’ key is being held.
Within this loop, the magnet level is decreased by the amount of time since the last frame, and updates the UIManager. Using yield return null means this loop runs every frame, therefore the level will be decreased by real time.
To change the functionality of the powerups, I used a foreach loop to get each Powerup Script on the child objects I stored previously in an Array. Then I could call a public method passing through a bool set to true.
Upon breaking out of the while loop, the same foreach loop is used but sets the bool to false. Then I start the MagnetOff Coroutine.
The MagnetOff Coroutine sets the bool to false. Then I wait for a cooldown time I set to 7 seconds, before running a while loop to recharge the magnet level and update the UI.
Over in the Powerup Script the public method I created, simply sets a bool which I then use in the Movement method.
The Movement method now has an if statement checking the bool. If true, I use transform.Translate to move the Powerup towards the Player in real time. Otherwise, the original downwards movement occurs.
Lastly, I duplicated the Thruster Slider and changed it to be suitable for my Magnet, then in the UIManager, I could store the Slider as a variable, and append it with the amount of time left.
I now had a functional magnet ability. The Translate function I used moves faster the further away it is, which I don’t mind. It acts as more of an aid to move things closer rather than completely bring them in. I may look at adding a visual feature to show the magnetism though, and of course creating better UI for the bottom right of the screen.