Magnetic Power Up!
In this article we will cover how to create a Power Up that will give the player the ability to attract other Power ups without moving.
Objective:
- When the player has enough magnetic “energy”, they can hold down a button to attract other Power Ups to them.
- When the player doesn’t have any magnetic “energy”, nothing will happen until they pick up a magnet Power Up, which will refill the magnet “energy” bar.
Each of the Power Ups has the same Power Up script that controls it straight downward movement and collision trigger. Since each Power Up has this script, we will controlled the magnetic movement in this script. So, we will need to get a handle on the player so we can access its position and magnet energy bar.
In the Update, we will need to create three variables that always needs to be updated. The first is a Vector2, which will hold the position of the Power Up. The second is another Vector2 is the target position, which is the player’s positions. The third is the speed the power up will move at towards the player.
Still in the Update, IF a public bool variable (isMagnetActive) from the player is true, we are going to set the new position of the Power Up to move towards the player’s position using Vector2.MoveTowards. Vector2.MoveTowards requires 3 things…
- Current position of the object (stored in pos).
- The current position of the object you want to move towards (stored in targetPos).
- The speed the object will move towards the other (magSpeed).
If the that bool is false, it will continue to travel down the screen.
In the Player script, we will now create two methods that sets the bool variable (isMagnetActive) to either true or false. It is important to make it public so the Power Up script can access it. Now we have a way to set isMagnetActive to true or false we can call it when we need it.
In the Update, we want to check to see if the C key is being held down. To do this, we will use GetKey instead of GetKeyDown. GetKeyDown only returns true each time the key is pressed down, instead of GetKey which returns true when the key is held down. If the C Key is being pressed we will use ActivateMagnet method. Now, you cannot see it in the image above since it is in the Use Status Bar method. If the Key C is not being pressed we call the Deactivate Magnet method. I am not going into the status bar script, but if you are interested click on link below.