Creating a One Button Magnet Feature that Collects All Powerups — 2D Galaxy Shooter in Unity — Part 02!

Chris Hilton
3 min readAug 28, 2021

--

Objective: Follow up to Part 01 in creating a magnet feature in Unity!

Let’s open up the ‘Powerup’ script and finish this feature off!

This is the Magnetise() method that is called from the ‘Player’ script when a game object with the tag ‘powerup’ has been found.

Let’s now create a variable that is going to handle the speed of the magnet and how quickly the powerups come to the player. We also need a bool trigger switch so that we can detect when the player is using the magnet and if they aren’t then the powerups are going to continue moving down the screen as per usual. Then we are going to need a Vector3 that is going to track the player’s transform position so the powerups can move towards them.

Then we are going to create an If statement to check our bool to see if the player has activated the magnet and if they have then run the PowerupMagnetMove() which is going to handle all the movement. Else, continue moving down the screen as mentioned.

Lastly, leave the existing If statement checking whether the powerup is below -6 on the Y-axis.

Let’s now run through the PowerupMagnetMove() method:

This is going to be called in the Update() method as we want to keep track of the player’s position every frame. Firstly we are going to assign our Vector3 variable playerPos to the players transform position.

Then we are going to create a new Vector3 ‘direction’ which is going to handle the vector calculations between the powerup and the player. We are also going to normalize our new vectordirection’ so that we limit the magnitude to 1 and the length remains the same.

Lastly, we are going to change the powerups transform position by taking the direction and multiplying it by the magnet speeds and Time.delta time.

Voila! This was quite a fun feature to implement. If I now make one tiny tiny adjustment to my code in this section:

We have an entirely new powerup!! It can be used to repel powerups… especially that negative one!

--

--