JS,Object跟随一个圆圈

Joh*_*han 4 javascript math animation geometry canvas

我试图让一个物体围绕另一个物体.我想,并不太难.但事实证明这个圆圈是螺旋式的......我可能使用了错误的公式,但我不确定应该选择哪一个......

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;
Run Code Online (Sandbox Code Playgroud)

当您执行此代码时,它似乎工作.对象围绕其父对象以弧形移动的每个帧.

然而,弧越来越大,越来越远.

我犯了什么错误?

Den*_*ret 5

您只是在浮点值中没有无限精度,并且没有无限小的角度步长.所以这个迭代计算不能准确.

没有确切的迭代解决方案:如果你尝试用初始方法提高精度,你仍然会得到分歧.

解决方案只是完全从角度计算每个步骤,这对于圆形来说很容易:

// init part, set your own values
var a = 0; // in radian
var r = 100; // radius, in pixels for example
var da = 1; // in radian. Compute this (once!) using r if you like to use an absolute speed and not a radial one


// each modification
a += da
x = r*Math.sin(a);
y = r*Math.cos(a);
Run Code Online (Sandbox Code Playgroud)