Gravity works weird

82 views Asked by At

I wanted to make simple gravity simulation in Unity, so I wrote this UnityScript (using information about gravity from 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);
    }
}

}

I created two GameObjects: Sol and Spacecraft (they are the same but Sol is static). After running my project, the path of Spacecraft looks like this:

enter image description here

but it should look similar to this:

enter image description here

What have I done wrong?

1

There are 1 answers

1
janw23 On

I solved my problem. I replaced

gameObject.GetComponent.<Rigidbody2D>().AddForce((inSOIof.transform.position - gameObject.transform.position) * totalForce/Mass * Time.deltaTime);

with

var direction : Vector3 = inSOIof.transform.position - transform.position;
    gameObject.GetComponent.<Rigidbody2D>().AddForceAtPosition((totalForce/Mass) * Time.deltaTime * direction.normalized, transform.position);