c# - 向鼠标当前位置旋转图像

标签 c# xna rotation

我正在尝试在 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 ,并根据角度对其进行更新,以便射击能够从该点向鼠标正确射击。

谢谢


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

playing with the super laser

using the superlaser on every enemy type

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

最佳答案

基本上,使用 Math.Atan2 .

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

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

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

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

关于c# - 向鼠标当前位置旋转图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13694003/

相关文章:

c# - PHP base64_decode C# 等价物

c# - 定时Windows服务由于运行多个线程而崩溃

c# - 重用 try catch 进行 wcf 调用

c# - Visual Studio 2012、Monogame C# 项目无法加载内容

javascript - 在滚动条上旋转一个元素,最轻的方法是什么?

ios - UIWebView - 在旋转变化时不调整内容的大小?

c# - 在 C# 中为 block blob 生成共享访问签名

c# - 如何检查某个位置是否有物体?

c# - "Cannot use fixed local inside lambda expression"

ios - 在 iOS swift 中旋转和混合图像