- Home /
Object movement- rounding error?
I made a simple 2d game that makes two planets orbit each other. To each of the planets, I attached the following script:
#pragma strict
var velocity = Vector2(0,0);
var target : Transform;
var weight = 4000;
private var acc = Vector2(0,0);
private var join = Vector2(0,0);
function Start() {
}
function FixedUpdate () {
var pos = transform.position;
join = target.transform.position - pos;
acc = 10 / join.sqrMagnitude * join.normalized;
velocity = velocity + acc;
pos = transform.position + velocity;
transform.position = pos;
}
The two planets are each set to have an opposite initial velocity(0.4 and -0.4), along the vertical axis, and are otherwise identical. This should make a cyclic orbit; however, when I set them to trace their paths, I get the following result:
The planets eventually meet in the middle and fling off into space. Do to the asymmetry, I believe this is an error of some sort, and not simply incorrectly coded orbital mechanics. Does anyone know a method to solve this problem or a workaround?
Answer by NoseKills · Oct 02, 2014 at 04:25 PM
You have 2 instances of that script running in 2 different objects.
The FixedUpdate gets called on one of the planets first and that planet moves. Then it gets called on the other one. At this point, since the other planet has already moved, the join
vector gets a different value for the second planet which leads to different acceleration, which leads to different speeds.
To fix this, you need to calculate the new position for both planets before moving either one (assuming the math is otherwise correct).