quality-control/Assets/Scripts/Magnet.cs

35 lines
890 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;
if (otherRb && otherRb.isKinematic == false)
2024-08-17 13:13:39 +00:00
{
2024-08-18 17:27:27 +00:00
if (!otherRb.GetComponent<Product>())
{
return;
}
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
}
}
}