2012-06-07 132 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

我不得不做一些三角形来获得正确的角度得到正确的方程。角度取决于运动弧的半径,因为更大的半径但恒定的角度会增加运动距离(不希望的行为)。我之前的解决方案(在编辑之前)是通过半径缩放角度,但这仍然会导致更大半径的移动。

当前的方法确保半径和速度在所有情况下保持不变。