【问题标题】:Rotating an image towards the mouse's current position向鼠标当前位置旋转图像
【发布时间】:2012-12-10 03:23:02
【问题描述】:

我正在尝试在 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);

虽然这使它旋转,但它不能正确跟随鼠标,并且行为怪异。

关于如何完成这项工作的任何提示?

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

谢谢


截图:

再次感谢,原来是个有趣的游戏。

【问题讨论】:

  • 你能贴一张武器的图片,让我们看看你想瞄准什么类型的形状吗?

标签: c# xna rotation


【解决方案1】:

基本上,使用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();

【讨论】:

  • 感谢您提供这个解释清楚的答案!当我的项目进一步发展时将发布屏幕截图。
猜你喜欢
  • 1970-01-01
  • 2012-05-14
  • 1970-01-01
  • 2013-09-08
  • 2013-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多