Magnet Script (rigidbody)

by | Jun 4, 2022 | code

This simple script allows a generic GameObject to act as a magnet. It will attract all the nearby objects with a rigidbody component attached to them.

 

using UnityEngine;
using UnityEngine.SceneManagement;

class MagnetMAGNET : MonoBehaviour
{
    const string AttractTagName = "Player";
    public float AttractRange = 10f;
    public float AttractForce = 30f;
    public GameObject areaOfEffect;

    void Start()
    {
        areaOfEffect.transform.localScale = new Vector3(AttractRange * 0.99f, AttractRange * 0.99f, AttractRange * 0.99f);
        areaOfEffect.transform.position = new Vector3(transform.position.x, AttractRange * 0.5f, transform.position.z);
    }



    private void FixedUpdate()
    {
        Collider[] Colliders = Physics.OverlapSphere(transform.position, AttractRange);
        foreach (Collider Collider in Colliders)
        {
            if (Collider.tag == AttractTagName)
            {
                Rigidbody rb = Collider.GetComponent(); 
                if (rb != null)
                {   
                    Attract(rb);
                }
                else
                {   
                    Debug.LogWarning("rigidbody component Not Found");
                }
            }

        }
    }
    private void Attract(Rigidbody rb)
    {
        float Distance = Vector3.Distance(rb.transform.position, this.transform.position);
        float TDistance = Mathf.InverseLerp(AttractRange, 0f, Distance); 
        float strength = Mathf.Lerp(0f, AttractForce, TDistance); 
        Vector3 FromObjectToMagnet = (this.transform.position - rb.transform.position).normalized; 
        rb.AddForce(FromObjectToMagnet * strength, ForceMode.Force);
    }

}

 

Related Posts

No Results Found

The page you requested could not be found. Try refining your search, or use the navigation above to locate the post.

0 Comments

0 Comments