Pickup Collect
Objective: Learn how to implement a system that when pressing a button, the player collects all powerups in the screen.
So today we are going to implement a system that makes it easier for our player to collect our powerups. When our player presses C all powerups in the screen are going to move towards our player.
private bool _isBeingCollect = false;
private GameObject _player;
private void Start()
{
_player = GameObject.FindGameObjectWithTag("Player");
if (_player == null)
Debug.LogError("Player is NULL on " + gameObject.name);
}
public void ActivateBeingCollected()
{
_isBeingCollect = true;
}
In order for us to move our Powerup towards the player, we first need it to know that the player exists. We’re adding the Player variable on void start, and assigning by finding our player based on his tag.
We also need to know, if the player ordered the powerup to be collected, we are going to move towards it, so we created a bool that handles that.
We created a method that sets our bool to true, that when our player presses the C key, we can simply activate our bool and change our movement based on that.
private void MovePowerUp()
{
if (_isBeingCollect == false || _player.activeInHierarchy == false)
transform.Translate(_powerUpSpeed * Time.deltaTime * Vector3.down);
else
{
Vector3 playerPos = _player.transform.position;
transform.position = Vector3.MoveTowards(transform.position, playerPos, _powerUpSpeed * Time.deltaTime);
}
if (transform.position.y < _minYPosition)
Destroy(gameObject);
}
So this is how its going to work. If we are not being collected or the player is not in the screen, we are simply going to move down. Why do we need to check if the player is active ? Well, if we tell our powerup to be collected and the player dies before the powerup reaches the player, we are going to have a problem. So if our player dies, we just move downwards.
Now, if our player is alive and we are being collected, we simply get the position of the player and use our Vector3.MoveTowards, by giving our position, and the player position. This way, we are going to move in his direction.
private void Update()
{
if (Input.GetKeyDown(KeyCode.C))
{
CollectAllPowerups();
}
//Rest of our update method
}
private void CollectAllPowerups()
{
PowerUp[] powerups = SpawnManager.Instance.transform.GetChild(1).GetComponentsInChildren<PowerUp>();
foreach (PowerUp powerup in powerups)
{
powerup.ActivateBeingCollected();
}
}
So we are checking on our Update if our player presses C. In case he does, we simply are getting all powerups in the screen, by creating an array of all powerups that are assigned to their parent, the Powerup Container.

After creating such array, we just run through all items in the array, and each item will call the ActivateBeingCollected method, which will change their _isBeingCollected bool to true.

Now our player has a way to call the incoming powerups towards him!