The next requirement is to beam the collectible to the Player when ‘C’ is pressed. Good thing there’s delegates that make it easy to communicate with the Power up to follow the Player.
On the Power up, I added these attributes:
[SerializeField]
private float _followSpeed = 3f;
private bool _followPlayer = false;
private Player _player;
The _followSpeed increases the speed of the pick up if the Player calls for it. I added _followPlayer to only follow the Player when this is true. Finally, we need a reference to the Player because the Power up needs the coordinates of the Player so it can follow it.
At the Start() method, I added a reference to the Player:
private void Start()
{
_player = GameObject.Find("Player").GetComponent<Player>();
if (_player == null)
{
Debug.Log("Player is null");
}
}
On the Update() method, I added this code to follow the player:
void Update()
{
if (!_followPlayer)
{
transform.Translate(Vector3.down * _speed * Time.deltaTime);
if (transform.position.y <= -6)
{
Destroy(gameObject);
}
}
else
{
Vector3 followDirection = (_player.transform.position - transform.position).normalized;
transform.Translate(followDirection * (_speed + _followSpeed) * Time.deltaTime);
}
}
To determine the direction of the player, you need to get the difference of the position between Player and the Power up. After that, you need to normalize it so the Power up doesn’t skip or blip its way to the Player.
Given that it’s a delegate, I added this for the Power up to listen to Player.CollectPickup():
public void OnEnable()
{
Player.CollectPickup += FollowPlayer;
}
private void OnDisable()
{
Player.CollectPickup -= FollowPlayer;
}
On the Player, you can simply declare the delegate and press C to send the message:
public static Action CollectPickup;void Update()
{
CalculateThruster();
CalculateMovement();
if (Input.GetKeyDown(KeyCode.Space) && CanFire())
{
FireLaser();
}
if (Input.GetKeyDown(KeyCode.C))
{
CollectPickup();
}
}
Now that this is done, the pick up can now follow the player when C is pressed.