Day 57: Attract Power Ups!

Tyler Smallwood
3 min readJun 28, 2021

Objective: While player holds ‘C’ all power ups will move toward player.

Let’s start with checking for the input from the player. This time we will want to watch out for the ‘C’ key being held. So instead of Input.GetKeyDown we just want Input.GetKey, which returns true while being held.

Now inside the PullPowerups function the first thing we want to do is start subtracting from our Magnet Power. Let’s create a few variables real quick. We need a variable for how fast the power ups will move toward the player, the max magnet power, the current magnet power and a bool to check if the player is allowed to use the magnet.

In start we will set the current magnet power to the max magnet power.

Now back in our function we will subtract the current magnet power from Time.deltaTime.

Next we have a check to see if the current magnet power is less than zero and if it is turn the bool to false and we’ll start the coroutine to build the power back up.

In the Coroutine we just use a while loop to slowly increase the current magnet power back up to the max magnet power. Once it is equal to or greater than the max magnet power, we turn the bool back to true and break out of the while loop.

Now when we check for the input, we can also check to see if the player is allowed to use the magnet.

Next will be to pull all the power ups. In our function we will create a local array variable and assign all the power ups in the scene to the array.

We will use a foreach loop to go through all of the local variable and set their movement toward the player. It’ll MoveTowards the player at the powerupspeed multiplied by Time.deltaTime.

The reason we use Input.GetKey(), as soon as you let go the power ups will continue it down.

Tomorrow we will cover the UI integration so the player knows when they are out of magnet power!

Thank you for reading! Have a wonderful day!

--

--

Tyler Smallwood

I am passonate on learning to program and use Unity to become a skillful Unity Developer