重力很奇怪

时间:2015-06-04 17:44:41

标签: unity3d unityscript gravity

我想在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);
    }
}

}

我创建了两个游戏对象:SolSpacecraft(它们是相同的,但Sol是静态的)。运行我的项目后,Spacecraft的路径如下所示:

enter image description here

但它应该与此类似:

enter image description here

我做错了什么?

1 个答案:

答案 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);