我试图让一个对象向鼠标旋转。问题是物体总是向左旋转一点点,要精确地多旋转 45 度。
因此,例如,如果我的鼠标位于对象应该位于北方的位置,因此旋转值 = 0,则对象向左旋转 45 度,因此 270 度并因此指向左,而它应该指向北/向上。
这是我的代码:
public override void Update()
{
base.Update();
GetMousePos();
SetRotation();
}
private void GetMousePos()
{
MouseState ms = Mouse.GetState();
_mousePos.X = ms.X;
_mousePos.Y = ms.Y;
}
private void SetRotation()
{
Vector2 distance = new Vector2();
distance.X = _mousePos.X - (_position.X + (_texture.Width / 2));
distance.Y = _mousePos.Y - (_position.Y + (_texture.Height / 2));
_rotation = (float)Math.Atan2(distance.Y, distance.X);
}
编辑:额外信息
当我的鼠标位于屏幕右侧时,这些值就会出现。对象应该指向东/右,但他指向北/上。
鼠标位置 X:1012
鼠标位置 Y:265
对象位置 X:400275
对象位置 Y:24025
旋转:0
编辑 2:如何使用 _rotation
public virtual void Draw(SpriteBatch spriteBatch)
{
int width = _texture.Width / _columns;
int height = _texture.Height / _rows;
Rectangle destinationRectangle = new Rectangle((int)_position.X, (int)_position.Y, width, height);
Rectangle sourceRectangle = new Rectangle((int)((_texture.Width / _columns) * _currentFrame), 0, width, height);
spriteBatch.Begin();
spriteBatch.Draw(_texture, destinationRectangle, sourceRectangle, Color.White, _rotation, new Vector2(width / 2, height / 2), SpriteEffects.None, 0);
spriteBatch.End();
}
编辑 3:工作修复的东西
protected void SetRotation()
{
MouseState mouse = Mouse.GetState();
Vector2 mousePosition = new Vector2(mouse.X, mouse.Y);
Vector2 direction = mousePosition - _position;
direction.Normalize();
_rotation = (float)Math.Atan2(
(double)direction.Y,
(double)direction.X) + 1.5f;
}