@dystroy 的解决方案是完全合法的,但有一种方法可以限制您的迭代方法,使其不会失控。
引入一个新变量 R,它是您希望对象环绕其父对象的固定半径。
var hypot = function(x, y) { return Math.sqrt(x*x + y*y); };
//Run this code only once!
var R = hypot(this.x - this.parent.x, this.y - this.parent.y);
然后可以添加圆的半径固定的约束:
//your original code
var dx = this.x - this.parent.x,
dy = this.y - this.parent.y,
r = Math.atan2(dy, dx);
//apply constraint:
//calculate what dx and dy should be for the correct radius:
dx = -R * Math.cos(r);
dy = -R * Math.sin(r);
//force this.x, this.y to match that radius.
this.x = this.parent.x + dx;
this.y = this.parent.y + dy;
//the radius will still be off after your update, but
//the amount by which it is off should remain bounded.
this.x = Math.sin(r) * this.speed + this.x;
this.y = (Math.cos(r) * this.speed * -1) + this.y;
您也可以在更新位置后应用约束。