效果
物体受到标签为RigidBody的一切物体的万有引力,引力满足距离平方反比规律。
用法
施加于被吸引的物体之上,物体需要添加RigidBody组件,物体重量由RigidBody的mass字段决定。万有引力系数在代码中以K表示。
注意
由于Vector3
类的枚举字段为float
型。float
型的指数位为8位,即范围为-2128~+2128。一旦物体间距离足够小,引力会急剧增大而导致数据溢出,此时的引力会出现不可预料的突变。因此在使用的过程中应该避免距离过近。实际上在现实中,当物体间的万有引力到达如此显著的程度时,其他基本力的影响将更加明显,此时仅模拟万有引力没有意义。
using UnityEngine;
using System.Collections;
public class BeingAttracted : MonoBehaviour {
public GameObject[] m_objects; //另一个物体
public Vector3 m_speed = new Vector3(0, 0, 0); //运动速度
private Vector3 m_attractiveForce; //二者之间的引力
private float m_mass; //这个物体的质量
private float m_forceCoefficient; //引力系数 k*M*m
private const float K = 25.0f;
// Use this for initialization
void Start () {
m_mass = this.GetComponent<Rigidbody>().mass;
this.GetComponent<Rigidbody>().velocity = m_speed;
}
// Update is called once per frame
void Update () {
m_objects = GameObject.FindGameObjectsWithTag("RigidBody");
m_attractiveForce = new Vector3(0, 0, 0);
foreach (GameObject attractingObject in m_objects)
if(attractingObject != this.gameObject)
GetAttractiveForce(attractingObject);
this.GetComponent<Rigidbody>().AddForce(m_attractiveForce);
//this.GetComponent<Rigidbody>().velocity = m_speed;
}
void GetAttractiveForce(GameObject attractingObject){
Vector3 distanceVector = attractingObject.transform.position - this.transform.position; //二者间的向量距离
Vector3 forceDirection = distanceVector.normalized; //引力方向
float sqrDistance = distanceVector.sqrMagnitude;
//if (sqrDistance != 0 && sqrDistance > 2)
//{
m_forceCoefficient = K * attractingObject.GetComponent<Rigidbody>().mass * m_mass;
m_attractiveForce += m_forceCoefficient / sqrDistance * forceDirection;
//}
Debug.Log("forceDirection" + forceDirection + ";distance" + distanceVector.sqrMagnitude + ";acceleration" + m_attractiveForce);
}
}