Attracting Power Ups to the Player

Thomas Kesler
3 min readJun 9, 2021

In the heat of the moment of battle, your player runs out of ammo and the nearest Powerup is on the other side of a line of missiles. Luckily, they have been saving the last the magnet charge for just this moment.

The ability to draw power ups to them is something the Players will learn to treasure. How to effect so many things at once may seem like at daunting task as a coder. But we can use C#’s Delegate and Event system to achieve our goal.

First, Let’s set up the PowerUp class. We will need a couple of Methods that will react to the events that we will setup later. These Methods will handle the Bool switching that will control the way PowerUp items will move.

Then when the _magnetized Bool is active, we setup up a Step (which controls the distance moved per frame) and use the Vector3.MoveTowards function to draw the power up towards the player. There are plenty of methods to grab the _player that we have discussed before and will skip here. Vector3.MoveTowards will be used when it is Magnetized and transform.Translate when it isn’t.

With a couple of lines in the Player class, we can set it up to send out Event calls. Since we are doing a simple event, we don’t have to worry about setup parameters for the Delegate. We can think of a Delegate as a custom Variable type that holds only Methods that match the paremeters the Delegate has. So we set up a Delegate MagnetPull() as the variable type and then set up two events, OnMagnetPull and OnMagnetStop both using the MagnetPull Delegate. This is like setting up two different INTs. And with them being static, we can access them from other scripts.

Back in the PowerUp Class, we assign the MagnetON() and MagnetOFF() to the respective events we want to trigger them. We do this in the Unity Method OnEnable(), this method is called by Unity whenever the GameObject it is attached to is enabled in the scene.

We also want to make sure to unassign the Methods in the OnDisable(). This will help conserve memory as you game grows.

We call the Event just as if it were a Method in the Class we are working in. Here you can see the implementation being used when the C key is pressed down or released. This code can be placed in Update() but was pulled into it’s own method called from Update() to keep it uncluttered.

We now have a simple way to affect many objects from a single script, what can you think to do with it?

--

--

Thomas Kesler

A Unity Developer with a fondness for Fantasy games and the challenge of pushing boundaries.