我正在尝试在 XNA 中制作一个简单的游戏。
我有一个播放器,旁边有 Sprite 表。 Sprite 表是一种带有尖端的武器。
如何让这个 Sprite 旋转并使其尖端面向鼠标位置?
float y2 = m_Mouse.Y;
float y1 = m_WeaponOrigin.Y;
float x2 = m_Mouse.X;
float x1 = m_WeaponOrigin.X;
// Get angle from mouse position.
m_Radians = (float) Math.Atan2((y2 - y1), (x2 - x1));
Drawing with:
activeSpriteBatch.Draw(m_WeaponImage, m_WeaponPos, r, Color.White, m_Radians, m_WeaponOrigin, 1.0f, SpriteEffects.None, 0.100f);
虽然这会使其旋转,但它不能正确跟随鼠标,并且表现得很奇怪。
关于如何实现这项工作有任何提示吗?
我遇到的另一个问题是定义一个点,即 Guzzle ,并根据角度对其进行更新,以便射击能够从该点向鼠标正确射击。
谢谢
截图:
再次感谢,结果证明这是一个有趣的游戏。
最佳答案
基本上,使用 Math.Atan2
.
Vector2 mousePosition = new Vector2(mouseState.X, mouseState.Y);
Vector2 dPos = _arrow.Position - mousePosition;
_arrow.Rotation = (float)Math.Atan2(dPos.Y, dPos.X);
概念证明(我对光标使用了加号纹理 - 不幸的是,它没有显示在屏幕截图上):
“什么是_arrow
?”
在该示例中,_arrow
的类型为 Sprite
,这在某些情况下可能会派上用场,并且肯定会让您的代码看起来更干净:
public class Sprite
{
public Texture2D Texture { get; private set; }
public Vector2 Position { get; set; }
public float Rotation { get; set; }
public float Scale { get; set; }
public Vector2 Origin { get; set; }
public Color Color { get; set; }
public Sprite(Texture2D texture)
{
this.Texture = texture;
}
public void Draw(SpriteBatch spriteBatch, GameTime gameTime)
{
spriteBatch.Draw(this.Texture,
this.Position,
null,
this.Color,
this.Rotation,
this.Origin,
this.Scale,
SpriteEffects.None,
0f);
}
}
声明:
Sprite _arrow;
发起:
Texture2D arrowTexture = this.Content.Load<Texture2D>("ArrowUp");
_arrow = new Sprite(arrowTexture)
{
Position = new Vector2(100, 100),
Color = Color.White,
Rotation = 0f,
Scale = 1f,
Origin = new Vector2(arrowTexture.Bounds.Center.X, arrowTexture.Bounds.Center.Y)
};
绘制:
_spriteBatch.Begin();
_arrow.Draw(_spriteBatch, gameTime);
_spriteBatch.End();
关于c# - 向鼠标当前位置旋转图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13694003/