在XNA中旋转球员

本文关键字:旋转 XNA | 更新日期: 2023-09-27 18:09:56

我一直在寻找如何正确地做到这一点的教程,谷歌一直是空的。也许这是一个非常简单的主题,但我不知道该怎么做。

到目前为止,我找到的代码看起来像这样:

        if (currentKeyboardState.IsKeyDown(Keys.A))
        {
            RotationAngle += 0.01f;
            float circle = MathHelper.Pi * 2;
            RotationAngle = RotationAngle % circle;
        }

只是,这没有多大作用。它来自MSDN。这是我能找到的最好的解决方案。

我想做的就是允许玩家旋转他们的飞船并朝另一个方向射击。我正在制作一款与小行星非常相似的游戏,但我目前只能朝一个方向射击。

任何帮助都将是感激的:)

编辑:这是我当前的播放器。cs:

using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace GameTest
{
    class Player
    {
        public Texture2D PlayerTexture;
        public Vector2 Position;
        public bool Alive;
        public int Health;
        public Vector2 origin;
        public float RotationAngle;
        KeyboardState currentKeyboardState;
        KeyboardState previousKeyboardState;
        public int Width
        {
            get { return PlayerTexture.Width; }
        }
        public int Height
        {
            get { return PlayerTexture.Height; }
        }

        public void Initialize(Texture2D texture, Vector2 position)
        {
            PlayerTexture = texture;
            Position = position;
            Alive = true;
            Health = 10;
            origin.X = PlayerTexture.Width / 2;
            origin.Y = PlayerTexture.Height / 2;
        }
        public void Update(GameTime gameTime)
        {
            RotationAngle += 10f;
            previousKeyboardState = currentKeyboardState;
            currentKeyboardState = Keyboard.GetState();
            float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
            if (currentKeyboardState.IsKeyDown(Keys.A))
            {
                //float circle = MathHelper.Pi * 2;
                //RotationAngle = RotationAngle % circle;
            }
            if (currentKeyboardState.IsKeyDown(Keys.D))
            {
                //rotation
            }
        }
        public void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(PlayerTexture, Position, null, Color.White, RotationAngle, origin, 1f, SpriteEffects.None, 0f);
        }
    }
}

在XNA中旋转球员

我猜你错过了'原点',或旋转中心:

RotationAngle += .5f;
float circle = MathHelper.Pi * 2;
RotationAngle = RotationAngle % circle;
Vector2 origin = new Vector2(texture.Width / 2, texure.Height / 2);
spriteBatch.Draw(texture, position, null, Color.White, RotationAngle, origin, 1.0f, SpriteEffects.None, 0f);

至于你想要拍摄的角度,你需要一些几何图形(像这样的东西,没有经过测试…但是如果我没记错的话):

Vector2 velocity = new Vector2(speed*Math.Cos(RotationAngle), speed*Math.Sin(RotationAngle));

同时,使用调试器确保旋转角度正确改变。