This article will show how to make all Power-Ups within range move towards the Player while the ‘C’ key is pressed.
In the PowerUp script, we need to add two variables. The first is a Transform that is used to locate the Player, and the other is a bool to know if the Power-Up should move to the Player.
The Power-Up needs to grab a reference to the Player’s transform to know what to move to when attracted.
We need two public methods that will get called telling the Power-Up to change how it moves. The first is to tell the Power-Up to move to the Player by setting the bool to true, and the other is to tell it to stop moving to the Player by setting the bool to false.
Now to implement the bool into the movement of the Power-Up. If the bool is false meaning, it should not move to the Player, and the Power-Up will do the normal movement of going down the screen. If the bool is true, the Power Up will then move towards the Player’s position.
Now we can create the script to detect and attract the Power-Ups to the Player. For detecting the Power-Ups, the script will need a Collider, so let’s have it require one. Now we need two variables. The first is a List of Power-Ups, which are the Power-Ups that are in range to be attracted. The second is a bool, so we will know if there is at least one Power-Up in range to be affected.
To detect if Power-Up is in range, we will check for the “Power Up” Tag on Colliders that enter the script’s Collider. Then grab their PowerUp script component, add them to the in range List, and let the script know that a Power-Up is in range.
Next, we need to make it so that when a Power-Up leaves the script’s Collider, it is removed from the in range List, stops moving to the Player, and check if the List is empty, meaning that there are no Power-Ups in range.
Now that the List of in range Power-Ups is having elements added, we can allow the Player to affect them when holding down the ‘C’ key while a Power-Up is in range by looping through the Power-Ups in the List and telling them to move to the Player. Then when the ‘C’ key is released while a Power-Up is in range, we loop through the List and tell them to stop moving to the Player.
To effect the Power-Ups, we need a child of the Player GameObject to attach the detection/attraction script.
We need to Tag the Power-Up Prefabs as “Power Up” to be recognized by the detector. And be added to or removed from the List of Power-Ups in range.
When the player holds down the ‘C’ key, the Power-Ups in range now move to the Player.