将图像旋转到鼠标的当前位置

时间:2012-12-04 00:06:08

标签: c# xna rotation

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

我有一个旁边有spritesheet的玩家。 spritesheet是一种带尖端的武器。

如何让这个精灵旋转,尖端朝向鼠标位置?

        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);

虽然这使它旋转,但它没有正确地跟随鼠标,并且表现得非常奇怪。

有关如何使这项工作的任何提示?

我的另一个问题是定义一个点,即枪口,并根据角度更新它,这样射击就会从该点向鼠标正确射击。

由于


截图: early, getting the mouse and cursor in place

playing with the super laser

using the superlaser on every enemy type

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

1 个答案:

答案 0 :(得分:3)

基本上,请使用Math.Atan2

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

_arrow.Rotation = (float)Math.Atan2(dPos.Y, dPos.X);

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

Pointing to cursor


“什么是_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();