Day 46|Magnet Pickup: 2D Space Shooter Series

Ted Lim
2 min readJun 16, 2021

To counteract the Destroy Powerups feature that we made in the last article, we’ll give the player a Magnet Pickup ability to collect powerups using the ‘C’ key.

Magnet Pickup

After players press the ‘C’ key, if there are powerups in a given radius of the player, the powerups will begin to move quickly toward the player. This makes it easier for players to collect powerups and avoid enemy lasers.

The 2 Key Methods

Physics2D.OverlapCircleAll

This method takes a Vector3 position and a float radius value. This will create a ring around our player that will get references to all colliders within its area. With the references to the colliders, we can access the powerups script and adjust their movement in our AttractPowerup IEnumerator function.

Vector3.MoveTowards

Filtering for the Powerup colliders, we need to access the powerup script to change their movement behavior. First, we turn off their normal downward movement. Then, we make the powerups constantly move towards the player with the Vector3.MoveTowards method. We give the method the powerup’s position, the endpoint (the player’s position), and a speed at which to perform the movement.

We use a while loop with the MoveTowards method because it needs to be called repeatedly to allow the powerup to reach its destination. Once the powerup is collected, we can exit the loop.

That’s the magnet feature! We’ve covered many ways to detect where objects are relative to one another in our game, and OverlapCircleAll is a great addition to them!

--

--