tags:

views:

430

answers:

2

I'm messing about with some stuff in XNA and am trying to move an object around asteroids-style in that you press left and right to rotate and up/down to go forwards and backwards in the direction you are pointing.

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

I'm guessing this is straight forward but I just can't figure it out. My "ship" class has the following properties which are note worthy here:

Vector2 Position
float Rotation

The "ship" class has an update method is where the input is handled and so far I've got 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 most appreciated!

+1  A: 

I believe the general formula is

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

Here is 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;
        }
    }
CDSO1
I've tried the following, but now it just seems to move along the x axis... :Sif (keyboard.IsKeyDown(Keys.Up)){ x += (float)Math.Cos(Rotation * Math.PI / 180) * 5; y += (float)Math.Sin(Rotation * Math.PI / 180) * 5;}if (keyboard.IsKeyDown(Keys.Down)){ x -= (float)Math.Cos(Rotation * Math.PI / 180) * 5; y -= (float)Math.Sin(Rotation * Math.PI / 180) * 5;}
Tom Allen
+5  A: 

OK, so here's how I did it (I knew there would be a non-trig 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;
}
Tom Allen
Good catch. That is the more appropriate way, being that it is utilizing the class libraries provided by the API you are using. Glad to hear you have resolved it
CDSO1