我想在Unity中进行简单的重力模拟,所以我编写了这个UnityScript(使用来自wikipedia.com的重力信息):
var Type : String;
var Mass : double;
var Density : double;
var Volume : double;
var Surface : double;
var Radius : double;
var isStatic : boolean;
var onRails : boolean;
var totalForce : double;
var gravCon : double;
var SOI : double;
var inSOIof : GameObject;
var Distance : double;
function Start () {
gravCon = 0.000000000066738480808080808080;
Time.timeScale = 3;
Radius = gameObject.transform.localScale.x;
Volume = (4/3) * (Mathf.Pow(Radius,3) * Mathf.PI);
Surface = 4 * Mathf.PI * Mathf.Pow(Radius,2);
Density = Mass / Volume;
if(isStatic == true){ onRails = false; gameObject.GetComponent.<Rigidbody2D>().isKinematic = true;}
}
function Update () {
if(isStatic == false){
if(onRails == false){
Distance = Mathf.Sqrt(Mathf.Pow(gameObject.transform.position.x - inSOIof.transform.position.x, 2)+Mathf.Pow(gameObject.transform.position.y - inSOIof.transform.position.y, 2));
totalForce = gravCon*((gameObject.GetComponent.<Specification>().Mass * inSOIof.GetComponent.<Specification>().Mass) / Mathf.Pow(Distance,2));
gameObject.GetComponent.<Rigidbody2D>().AddForce((inSOIof.transform.position - gameObject.transform.position) * totalForce/Mass * Time.deltaTime);
}
}
}
我创建了两个游戏对象:Sol
和Spacecraft
(它们是相同的,但Sol
是静态的)。运行我的项目后,Spacecraft
的路径如下所示:
但它应该与此类似:
我做错了什么?
答案 0 :(得分:2)
我解决了我的问题。 我换了
gameObject.GetComponent.<Rigidbody2D>().AddForce((inSOIof.transform.position - gameObject.transform.position) * totalForce/Mass * Time.deltaTime);
与
var direction : Vector3 = inSOIof.transform.position - transform.position;
gameObject.GetComponent.<Rigidbody2D>().AddForceAtPosition((totalForce/Mass) * Time.deltaTime * direction.normalized, transform.position);