用于在 Unity 中创建刚体磁铁的 C# 脚本
下面是针对 Unity 中的刚体生成类似 magnet 行为的脚本:
脚步
- 创建 一个新脚本,将其命名为 SC_RigidbodyMagnet,然后将以下代码粘贴到其中:
SC_RigidbodyMagnet.cs
using System.Collections.Generic;
using UnityEngine;
public class SC_RigidbodyMagnet : MonoBehaviour
{
public float magnetForce = 100;
List<Rigidbody> caughtRigidbodies = new List<Rigidbody>();
void FixedUpdate()
{
for (int i = 0; i < caughtRigidbodies.Count; i++)
{
caughtRigidbodies[i].velocity = (transform.position - (caughtRigidbodies[i].transform.position + caughtRigidbodies[i].centerOfMass)) * magnetForce * Time.deltaTime;
}
}
void OnTriggerEnter(Collider other)
{
if (other.GetComponent<Rigidbody>())
{
Rigidbody r = other.GetComponent<Rigidbody>();
if(!caughtRigidbodies.Contains(r))
{
//Add Rigidbody
caughtRigidbodies.Add(r);
}
}
}
void OnTriggerExit(Collider other)
{
if (other.GetComponent<Rigidbody>())
{
Rigidbody r = other.GetComponent<Rigidbody>();
if (caughtRigidbodies.Contains(r))
{
//Remove Rigidbody
caughtRigidbodies.Remove(r);
}
}
}
}
按 Play,然后使用 SC_RigidbodyMagnet 脚本将对象移动到刚体上,注意刚体是如何被拉入的。