2012-06-07 130 views
1

這似乎是一個簡單的觸發問題,但無論出於何種原因,事情都沒有解決。圍繞一個點

我試圖簡單地有一個對象在用戶按下A/D鍵(圍繞鼠標圓周運動,同時仍然面對鼠標)的給定點旋轉。

這裏是到目前爲止,我已經試過代碼(所有的數學函數接受和返回弧度):

if (_inputRef.isKeyDown(GameData.KEY_LEFT)) 
{ 
    x += 2 * Math.cos(Math.atan2(mouseY - y, mouseX - x) - Math.PI * 0.5); 
    y += 2 * Math.sin(Math.atan2(mouseY - y, mouseX - x) - Math.PI * 0.5); 
} 
else if (_inputRef.isKeyDown(GameData.KEY_RIGHT)) 
{ 
    x += 2 * Math.cos(Math.atan2(mouseY - y, mouseX - x) + Math.PI * 0.5); 
    y += 2 * Math.sin(Math.atan2(mouseY - y, mouseX - x) + Math.PI * 0.5); 
} 

並完成同樣的事情更優雅的方法:

if (_inputRef.isKeyDown(GameData.KEY_LEFT)) 
{ 
    x += 2 * Math.sin(Math.atan2(mouseY - y, mouseX - x)); 
    y -= 2 * Math.cos(Math.atan2(mouseY - y, mouseX - x)); 
} 
else if (_inputRef.isKeyDown(GameData.KEY_RIGHT)) 
{ 
    x -= 2 * Math.sin(Math.atan2(mouseY - y, mouseX - x)); 
    y += 2 * Math.cos(Math.atan2(mouseY - y, mouseX - x)); 
} 

現在,他們都是一種工作,物體圍繞鼠標旋轉,同時始終面向鼠標,但如果有足夠的時間按住沙漏按鈕,則會變得越來越明顯t物體也從鼠標旋轉離開,彷彿它被推開。

我不知道這是爲什麼以及如何解決它。

任何見識都被讚賞!

+1

你確定它不是浮點漂移嗎? 「給予足夠的時間」多長時間。這可能是事前或事後發生的事情(我注意到'x'和'y'都是'+ =',所以不清楚還有什麼影響最終值) –

+0

我認爲主要問題是誤解了什麼是strafing 。 Strafing:玩家沿着其y軸直線移動,同時保持朝向一個點的方向。 所以解決方案是,旋轉面對鼠標,然後移動到左側或右側的對象。它不是一個單一的計算。它的兩個簡單步驟。 –

+0

這基本上是他目前正在做的,這導致了所描述的擴大的圓形運動的問題。 – Torious

回答

1

我認爲你現在的方法只有在你採取'無限小'的步驟時纔有效。就像現在一樣,每個運動都與「鼠標向量」垂直,從而增加了鼠標和對象之間的距離。

的溶液。將計算新的位置,同時保持到鼠標的距離不變,通過圍繞鼠標位置:

// position relative to mouse 
var position:Point = new Point(
    x - mouseX, 
    y - mouseY); 

var r:Number = position.length; // distance to mouse 

// get rotation angle around mouse that moves 
// us "SPEED" unit in world space 
var a:Number = 0; 
if (/* LEFT PRESSED */) a = getRotationAngle(SPEED, r); 
if (/* RIGHT PRESSED */) a = getRotationAngle(-SPEED, r); 
if (a > 0) { 

    // rotate position around mouse 
    var rotation:Matrix = new Matrix(); 
    rotation.rotate(a); 
    position = rotation.transformPoint(position); 
    position.offset(mouseX, mouseY); 

    x = position.x; 
    y = position.y; 
} 

// elsewhere... 

// speed is the distance to cover in world space, in a straight line. 
// radius is the distance from the unit to the mouse, when rotating. 
private static function getRotationAngle(speed:Number, radius:Number):Number { 
    return 2 * Math.asin(speed/(2 * radius)); 
} 

上面使用Matrix繞所述鼠標(x, y)位置位置。當然,如果需要,您可以使用相同的原則而不使用Matrix

我不得不做一些三角形來獲得正確的角度得到正確的方程。角度取決於運動弧的半徑,因爲更大的半徑但恆定的角度會增加運動距離(不希望的行爲)。我之前的解決方案(在編輯之前)是通過半徑縮放角度,但這仍然會導致更大半徑的移動。

當前的方法確保半徑和速度在所有情況下保持不變。