Power-Ups Magnet — Player pulling objects to collect (2D Space Shooter)
2 min readApr 8, 2023
- Magnet system
- Enemy Shooting Power Ups
Very simple magnetic field that attracts collectibles towards players. Here we focus mainly on the power-ups, but it also applies for ammo and health packs. On the player’s side, we got a game object which is a magnetic field, toggled on and off with the C key.
void MagneticFieldOn()
{
if (Input.GetKey(KeyCode.C) && !_magnetOnCD)
{
_magneticCollider.gameObject.SetActive(true);
}
else if (Input.GetKeyUp(KeyCode.C) && !_magnetOnCD)
{
_magnetOnCD = true;
StartCoroutine(MagneticFieldDelay());
}
}
IEnumerator MagneticFieldDelay()
{
yield return new WaitForSeconds(1.0f);
_magneticCollider.SetActive(false);
yield return new WaitForSeconds(0.05f);
_magneticCollider.SetActive(true);
yield return new WaitForSeconds(0.6f);
_magneticCollider.SetActive(false);
yield return new WaitForSeconds(0.05f);
_magneticCollider.SetActive(true);
yield return new WaitForSeconds(0.2f);
_magneticCollider.SetActive(false);
_magnetOnCD = false;
}
On the Power-Up script, the power up moves normally if no magnet is found, but moves towards the player when it does.
void Update()
{
if (!_magnetFound)
{
transform.Translate(Vector3.down * _speed * Time.deltaTime);
}
else if (_magnetFound)
{
MoveTowardsPlayer();
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
Player player = other.transform.GetComponent<Player>();
AudioSource.PlayClipAtPoint(_powerUpClip, transform.position);
if (player != null)
{
switch(powerUpID)
{
case 0:
player.ActivateTripleShot();
break;
case 1:
player.ActivateBoost();
break;
case 2:
player.ActivateShield();
break;
case 3:
player.SlowDown();
break;
case 4:
player.ActivateHomingMissile();
break;
}
}
Destroy(this.gameObject);
}
else if (other.tag == "Enemy Laser")
{
AudioSource.PlayClipAtPoint(_explosionClip, transform.position);
Destroy(this.gameObject);
}
else if (other.tag == "PlayerMagnet")
{
_magnetFound = true;
}
else
{
_magnetFound = false;
}
}
void MoveTowardsPlayer()
{
transform.position = Vector3.Lerp(this.transform.position, _playerTransform.transform.position, 1.5f * Time.deltaTime);
}
In case the magnet stops, the power up stops moving towards the player and returns to its normal state of falling down at its own speed. This can sometimes be helpful as, during testing, many enemies have shot power ups that are being pulled towards the player.