I’m trying to get an object to circle around another object. Not too hard, I figured. But it turns out the circle is a spiral… I’m probably using the wrong formula but I am not sure which one I should take instead…
var dx = this.x - this.parent.x,
dy = this.y - this.parent.y,
r = Math.atan2(dy, dx);
this.x = Math.sin(r) * this.speed + this.x;
this.y = (Math.cos(r) * this.speed * -1) + this.y;
When you execute this code, it would appear to work. Each frame the object moves in an arc around it’s parent object.
However, the arc gets bigger and bigger, increasing it’s distance more and more.
What mistake am I making?
You simply don’t have infinite precision in your float values, and you don’t have infinitely small angular steps. So this iterative calculum cannot be exact.
There is no exact iterative solution : if you try to improve the precision with your initial approach, you’ll still get a divergence.
The solution is simply to compute each step completely from the angulum, which is easy for a circle :