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:55:28 +00:00
|
|
|
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);
|
2024-08-17 14:39:05 +00:00
|
|
|
float forceMagnitude = strength * (1.0f / dirSq);
|
|
|
|
Vector3 force = dir.normalized * forceMagnitude;
|
2024-08-17 13:13:39 +00:00
|
|
|
|
2024-08-17 14:39:05 +00:00
|
|
|
otherRb.AddForce(-force);
|
2024-08-17 14:13:26 +00:00
|
|
|
|
|
|
|
if (rb)
|
2024-08-17 14:39:05 +00:00
|
|
|
rb.AddForce(force);
|
2024-08-17 13:13:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|