- Home /
addforce in a solar system cause framerate to drop to zero over time.
I have just made a little solar system with a gravity script. I get one mysterious error I cannot debug:
"rigidbody.force assign attempt for "Planet" is not valid. Input position is {Nan,NaN,NaN}".
Here is the script:
var GravitationalConstant = 0.0000000000667300; var Startspeed = Vector3(0,0,30);
function getGravity(m1,m2,Radius) { //the standard formula for gravitational force var gForce = GravitationalConstant*((m1*m2)/(Radius*Radius)); return gForce; }
function Start() { transform.rigidbody.velocity = Startspeed; }
function FixedUpdate () { var bodies = GameObject.FindGameObjectsWithTag ("mass"); var position1 = transform.position; //this position var mass1 = transform.rigidbody.mass;
//run through all gravitational enteties in the local space for (var body in bodies) { //find the gravitational force as a vector from each body //first we need the distance and mass of the object var diffVector = (body.transform.position - position1); var distanceLength = diffVector.magnitude; var mass2 = body.transform.rigidbody.mass;
var gForce = getGravity(mass1,mass2,distanceLength); //here is the line that cause all the problems: transform.rigidbody.AddForce(diffVector.normalized * gForce); }
}
The last line with AddForce is the one that causes the problems. It all works in the editor when I press play, but I cant compile it and after a few seconds the framerate drops from 500 to 3 (gradually)
Answer by skovacs1 · Oct 13, 2010 at 02:32 PM
You are dividing by 0 which will return NaN. Get gravity divides by radius * radius which is passed in diffVector.magnitude which is 0 when body.transform.position = transform.position.
You are not checking to ignore when body is gameObject. Also, you could still potentially have objects at the same position theoretically and you should check to avoid that. Something like:
if(diffVector == Vector3.zero) continue;
Thank you! Of course I get divide by zero when it checks on it self. I would not have seen that my self.
Cheers!