Collecting Powerups

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.

if (Input.GetKey(KeyCode.C))
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.





Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to Implement MVC Architecture in Java?

GCP- GCE instance template setup

CyberChef and GitHubCity Contributions

Super Fan or Adrift? Why and How you Should be Segmenting Your DevRel Community

Zen of Python : The Hard Way Is Easier

Exactly-Once Semantics with Apache Kafka

Let’s talk about the GO lang, google’s language!

Preface: Necessity is the Mother of Invention

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
Christian Carter

Christian Carter

More from Medium

Loading Scenes In Unity

Light her up — Adding emissions to your game objects using photoshop and blender


Pushing a box