2012-04-27 6 views
4

私は別のオブジェクトを囲むようにオブジェクトを取得しようとしています。それほど難しくないと思った。しかし、それはあなたがこのコードを実行すると、それが表示されますJS、円の後のオブジェクト

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; 

...スパイラルです...私はおそらく間違った式を使用していますが、私は、私が代わりに取るべきかわからないですサークルが判明します働く各フレームは、オブジェクトが親オブジェクトの周りを円弧状に移動します。

しかし、アークはますます大きくなり、距離がますます大きくなります。

私は間違いをしていますか?

答えて

5

フロート値に無限の精度を持たず、角度ステップが無限に小さいだけではありません。したがって、この反復結石は正確ではありません。

正確な反復解はありません。最初のアプローチで精度を向上させようとすると、依然として発散します。

ソリューションは、円のために簡単ですangulum、から完全に各ステップを計算するだけである:dystroyのソリューション@

// 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); 
+0

これは、私が基本的に行ったすべての変更が悪化した理由を説明しています...コードは正解でしたが、あらかじめ十分なものではありません...あなたの変数はどのように私のものと一致しますか? aは度での角度です、と思いますか? rは半径、daは速度です。 – Johan

+0

この種の反復計算では、数学的には正確な精度が得られません。 –

+1

は、角度をラジアンで表し、rを半径とし、daを角速度とする。 –

2

は完全に合法ですが、なるように、あなたの反復的なアプローチを制限する方法がありますそれは制御から渦巻くことはありません。

新しい変数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; 

あなたはまた、位置を更新した後、制約を適用することができます。

+0

私はこのanwserを覚えています..ありがとう! – Johan

+0

あなたはまだ全角度位置の相違があります。基本的なルールは、積分を近似値で置き換える必要があります。 –

+0

まだ私はこの反復的なアプローチの背後にある数学を理解していません。リンクはありますか? – Raffaele

関連する問題