2D Galaxy Shooter P2: Picking up Power-ups by holding a button!

For today’s challenge, I implemented a power-up pick-up feature!

When holding down the ‘C’ key, we can now have all power-ups, currently active, in the scene come to us.

In the player script, I created a new function called PickUpPowerUp(). It will hold all the logic to find the power-up and follow the player when the C button is held down.

I first need to find active power-ups that spawn in:

var powerups = GameObject.FindGameObjectsWithTag(“Powerup”);

So with every power-up prefab, I gave it a “Powerup” tag so they can easily be located. We find any game objects with the tag and cache them to the powerups variable.

If powerups equal to null, then we want to return, as in, do nothing.

if(powerups == null) return;

If powerups do not equal null, we want to search for all the power-ups currently active in the scene.

if(powerups != null)
{
foreach (var powerup in powerups)
{
//Find length between the powerup and the player
//pull the position of the powerup to the player position
}
}

We then calculate the logic inside the foreach loop.

Vector3 direction = powerup.transform.position — transform.position;
powerup.transform.position -= direction.normalized * _pickUpSpeed * Time.deltaTime;

We subtract the power-up position from the player position and cache it to a vector. We then want the power-up position to subtract its position from the player direction (the new vector we created) with speed and time.

We also normalize the direction because we want the magnitude to equal one. It keeps all directions the same. Most notably when the direction is diagonal.

Now, we need to add the input in the Update() function to use this feature!

if (Input.GetKey(KeyCode.C))
{
_isPickingUpPowerup = true;
PickUpPowerUp();
}
else if (Input.GetKeyUp(KeyCode.C))
{
_isPickingUpPowerup = false;
}

If I press and hold down the C key, make sure that _isPickingUpPowerup is true. Then we want to call the PickUpPowerUp() function we created. When we lift the C key, then _isPickingUpPowerup is false.

And that is all! It works like a charm when testing.

My biggest take on this is the fact that I am becoming more comfortable with Vectors! Vectors from the beginning of my game development journey have been shakey. I am happy to say that it isn’t as bad anymore!

That is all for today. Thank you for your time!

Hello everyone, My name is Gabriel Perez, I am a Unity Developer and a creator who is always learning and experimenting.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store