quality-control/Assets/Scripts/Magnet.cs

30 lines
743 B
C#
Raw Normal View History

2024-08-17 13:13:39 +00:00
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Magnet : MonoBehaviour
{
Rigidbody _rb;
Rigidbody rb { get { if (!_rb) _rb = GetComponent<Rigidbody>(); return _rb; } }
public float strength = 100;
private void OnTriggerStay(Collider other)
{
var otherRb = other.attachedRigidbody;
2024-08-17 14:13:26 +00:00
if (otherRb)
2024-08-17 13:13:39 +00:00
{
2024-08-17 14:13:26 +00:00
Vector3 dir = otherRb.position - transform.position;
2024-08-17 13:13:39 +00:00
float dirSq = Vector3.SqrMagnitude(dir);
float forceMagnitude = strength * (1.0f / dirSq);
Vector3 force = dir.normalized * forceMagnitude;
2024-08-17 13:13:39 +00:00
otherRb.AddForce(-force);
2024-08-17 14:13:26 +00:00
if (rb)
rb.AddForce(force);
2024-08-17 13:13:39 +00:00
}
}
}