Unity 3D Rigidbody Magnet

Unity 3D Rigidbody Magnet

by NSDG • Oct 16, 2019 • 0 Comments
72

Below is the script that generates magnet-like behaviour toward Rigidbodies in Unity 3D:

Steps

  • Create new script, call it SC_RigidbodyMagnet then paste the code below inside it:

SC_RigidbodyMagnet.cs

using System.Collections.Generic;
using UnityEngine;

public class SC_RigidbodyMagnet : MonoBehaviour
{
    public float magnetForce = 100;

    List<Rigidbody> caughtRigidbodies = new List<Rigidbody>();

    void FixedUpdate()
    {
        for (int i = 0; i < caughtRigidbodies.Count; i++)
        {
            caughtRigidbodies[i].velocity = (transform.position - (caughtRigidbodies[i].transform.position + caughtRigidbodies[i].centerOfMass)) * magnetForce * Time.deltaTime;
        }
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.GetComponent<Rigidbody>())
        {
            Rigidbody r = other.GetComponent<Rigidbody>();

            if(!caughtRigidbodies.Contains(r))
            {
                //Add Rigidbody
                caughtRigidbodies.Add(r);
            }
        }
    }

    void OnTriggerExit(Collider other)
    {
        if (other.GetComponent<Rigidbody>())
        {
            Rigidbody r = other.GetComponent<Rigidbody>();

            if (caughtRigidbodies.Contains(r))
            {
                //Remove Rigidbody
                caughtRigidbodies.Remove(r);
            }
        }
    }
}

  • Create new GameObject and assign SC_RigidbodyMagnet script to it
  • Add a Sphere Collider to a newly created Object, mark it as Trigger then increase its radius
  • Create couple of Cubes and add a Rigidbody component to them

Pres Play then move the Object with SC_RigidbodyMagnet script over the Rigidbodies, note how the Rigidbodies are being pulled in.