Sprite 如何使精灵指向鼠标。xNAC#

Sprite 如何使精灵指向鼠标。xNAC#,sprite,trigonometry,Sprite,Trigonometry,如果你看这张图,我需要通过知道直角三角形所有边的长度来求出角度A 我不懂三角,需要帮助 你的帖子里实际上有两个问题 如何使精灵指向鼠标。XNA C# 您必须计算精灵位置和鼠标位置之间的方向。 这可以通过三角函数来实现。在本例中:Arctangens2 让我们使用数学库: MouseState mouseState = Mouse.GetState(); Math.Atan2((double)mouseState.Y - sprite.Y, (double)mouseState.X - sprit

如果你看这张图,我需要通过知道直角三角形所有边的长度来求出角度A


我不懂三角,需要帮助

你的帖子里实际上有两个问题

如何使精灵指向鼠标。XNA C#

您必须计算精灵位置和鼠标位置之间的方向。 这可以通过三角函数来实现。在本例中:Arctangens2

让我们使用数学库:

MouseState mouseState = Mouse.GetState();
Math.Atan2((double)mouseState.Y - sprite.Y, (double)mouseState.X - sprite.X); //this will return the angle(in radians) from sprite to mouse.
在三角学示例中,您将看到这些值实际上是:

Math.Atan2(BC, AC);

我希望这有帮助

干杯


TomHashNL

我发现我的最终解决方案是:

Vector2 direction = targetPosition - currentPosition;
direction.Normalize();
float rotationInRadians = (float)Math.Atan2((double)direction.Y, 
                             (double)direction.X) + MathHelper.PiOver2;
RotationRadians是一个原始值,可以传递给sprite批处理以获得正确的旋转量——不需要进一步的代码。此外,如果在角落而不是中间旋转精灵,您可能会注意到错误的结果

Vector2 direction = targetPosition - currentPosition;
direction.Normalize();
float rotationInRadians = (float)Math.Atan2((double)direction.Y, 
                             (double)direction.X) + MathHelper.PiOver2;