This tutorial covers pressing the “C” key to draw power up collectables to the player. This is all handled inside the Powerup script. First add a variable for the player. This will be used to know the position of the player so that it can move towards the player. Also, add a Start function if it is not there. In the Start function set the player variable and verify it.
private Player _player;
private void Start()
_player = GameObject.FindWithTag("Player").GetComponent<Player>();
if (_player == null)
Debug.LogError("Player is NULL in Powerup.");
Next, in the Update function where the movement of the powerup is controlled you are going to update it. First by adding an if statement to see if the “C” key is being pressed. If it is create a new Vector3 variable that will be players position minus the powerups position. This will give you the vector pointing to the the player from the powerup. Next, normalize the vector. This will make sure the powerup is moving at a consistent speed towards the player no matter how far away it is. Then call the transform.Translate function to move the powerup. This will be just like the regular movement but instead of using the down vector you will use the new vector you created. After that add an else statement and add the regular movement into there.
Vector3 directionVector = _player.transform.position -
transform.Translate(directionVector * _speed * Time.deltaTime);
transform.Translate(Vector3.down * _speed * Time.deltaTime);
With those changes the powerup will now move towards the player when the “C” key is pressed down.