Adding a powerup magnet to my space shooter

I want to make it easier for my player to collect powerups, and the best way to do that would to create some sort of functionality where the player can use a “magnet” to attract nearby powerups. This is pretty simple to implement.

I created an empty object as a child of the player object and gave it a circle collider. The circle collider will serve as the magnet’s radius, so I made it a bit larger than the player. Then in the player script, I made a variable to reference the magnet object. In the Update method, I’m checking if the ‘C’ key is held down. If it is, it activates the magnet’s circle collider component. When the key is released, it deactivates the collider. That’s all I need to do in the player script.

The collision logic is handled in the powerup script. I added a new method, called OnTriggerStay2D, which is a built-in method that is called every frame that one collider is intersecting with another. If the other object is the player magnet, the powerup will move towards the object, which will eventually cause it to hit the player’s collider.