How to create a Magnet Effect
Lazy man’s easy power up collecting
1 min readJul 8, 2021
In this article we created an Magnet Effect to collect power ups in our game when we press the C-key.
Pseudocode for the Magnet Effect Logic
Player script
if C is pressed
then find objects with tag powerup
enable magnet in Powerup script
Powerup script
if magnet is enabled
then move to player
else just keep moving downwards
Magnet Effect Code
Player Script
This code finds all objects with the tag powerup and then foreach of those objects enables the magnet.
if (Input.GetKeyDown(KeyCode.C))
{
GameObject[] PowerUps = GameObject.FindGameObjectsWithTag(“PowerUp”);
//enable magnets on powerups
foreach (GameObject PowerUp in PowerUps)
{
PowerUp.GetComponent<Powerup>().EnableMagnet();
}
}
Powerup Script
The public method so we can activate the magnet from our player script:
public void EnableMagnet()
{
_isMagnetActive = true;
}
This part changes the rigidbody velocity when the magnet is active. In Update():
if (_isMagnetActive)
{
_direction = (_player.transform.position — this.transform.position).normalized * _magnetSpeed;
rb.velocity = _direction;
}
else
{
//move down
transform.Translate(Vector3.down * _speed * Time.deltaTime);
}