向鼠标当前位置旋转图像

Sai*_*aku 2 c# xna rotation

我正在尝试在 XNA 中制作一个简单的游戏。

我有一个旁边有精灵表的播放器。精灵表是一种带有尖端的武器。

我怎样才能让这个精灵旋转并使其尖端面向鼠标位置?

        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);
Run Code Online (Sandbox Code Playgroud)

虽然这使它旋转,但它不能正确跟随鼠标,并且表现得很奇怪。

关于如何进行这项工作有任何提示吗?

我遇到的另一个问题是定义一个点,即枪口,并根据角度更新它,以便射击将从该点向鼠标正确射击。

谢谢


截图: 尽早将鼠标和光标放置到位

玩超级激光

对每种类型的敌人使用超级激光

再次感谢,结果证明这是一个有趣的游戏。

nee*_*eKo 5

基本上,使用Math.Atan2.

Vector2 mousePosition = new Vector2(mouseState.X, mouseState.Y);
Vector2 dPos = _arrow.Position - mousePosition;

_arrow.Rotation = (float)Math.Atan2(dPos.Y, dPos.X);
Run Code Online (Sandbox Code Playgroud)

概念证明(我对光标使用了加号纹理 - 不幸的是它没有显示在屏幕截图上):

指向光标


“什么是_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);
    }
}
Run Code Online (Sandbox Code Playgroud)

宣布:

Sprite _arrow;
Run Code Online (Sandbox Code Playgroud)

发起:

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)
        };
Run Code Online (Sandbox Code Playgroud)

画:

_spriteBatch.Begin();
_arrow.Draw(_spriteBatch, gameTime);
_spriteBatch.End();
Run Code Online (Sandbox Code Playgroud)