quality-control/Assets/Scripts/Magnet.cs

29 lines
685 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 force = strength * (1.0f / dirSq);
otherRb.AddForce(-dir * force);
2024-08-17 14:13:26 +00:00
if (rb)
rb.AddForce(dir * force);
2024-08-17 13:13:39 +00:00
}
}
}