XNA Vector2 rotation question

I am doing some stuff in XNA and trying to move an object around the asteroids in that you push left and right to rotate and up / down to go back and forth in the direction you point.

I have a rotation of the sprite, but I can't get the object to move in the direction you pointed it, it always moves up and down on the x = 0 axis.

I guess this is straight forward, but I just can't figure it out. My ship class has the following properties that deserve attention:

Vector2 Position
float Rotation

      

The ship class has an update method where the input is handled and so far I have the following:

public void Update(GameTime gameTime)
{
    KeyboardState keyboard = Keyboard.GetState();
    GamePadState gamePad = GamePad.GetState(PlayerIndex.One);

    float x = Position.X;
    float y = Position.Y;

    if (keyboard.IsKeyDown(Keys.Left))  Rotation -= 0.1f;
    if (keyboard.IsKeyDown(Keys.Right)) Rotation += 0.1f;
    if (keyboard.IsKeyDown(Keys.Up))    ??;
    if (keyboard.IsKeyDown(Keys.Down))  ??;

    this.Position = new Vector2(x, y);
}

      

Any help would be greatly appreciated!

+2


a source to share


3 answers


OK, so this is how I did it (I knew there would be a non-triggered solution!)



float x = Position.X;
float y = Position.Y;

Matrix m = Matrix.CreateRotationZ(Rotation);

if (keyboard.IsKeyDown(Keys.Left))  Rotation -= 0.1f;
if (keyboard.IsKeyDown(Keys.Right)) Rotation += 0.1f;
if (keyboard.IsKeyDown(Keys.Up))
{
    x += m.M12 * 5.0f;
    y -= m.M11 * 5.0f;
}
if (keyboard.IsKeyDown(Keys.Down))
{
    x -= m.M12 * 5.0f;
    y += m.M11 * 5.0f;
}

      

+5


a source


I realize this is a little old, but I was still running into this and I figured I'd add this for the sake of completeness.

Instead of using:

X += (float)Math.Cos(Angle * PI / 180.0f) * 5f;
Y += (float)Math.Sin(Angle * PI / 180.0f) * 5f;

      

You can use:



this.Position.X += (float)(Math.Cos(this.Angle - MathHelper.PiOver2) * 2f);
this.Position.Y += (float)(Math.Sin(this.Angle - MathHelper.PiOver2) * 2f);

      

I seem to be moving forward anyway.

From this tutorial (link to part 3 because it has links to the first two).

+2


a source


I believe the general formula is

X += cos(Angle * PI/180)*Speed
Y += sin(Angle * PI/180)*Speed

      

Here's an example:

 public partial class Form1 : Form
    {
        private float X = 10, Y=10;
        private float Angle = 45f;
        float PI = 3.141f;


        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {           
            X += (float)Math.Cos(Angle * PI / 180.0f)*5f;
            Y += (float)Math.Sin(Angle * PI / 180.0f) * 5f;

            button1.Top = (int)X;
            button1.Left = (int)Y;
        }
    }

      

+1


a source







All Articles