Mården
Mården

Reputation: 31

Classic "Asteroids" controls - ship moving sideways?

I'm teaching myself to make a 2D shooter game a la "Asteroids", in other words: Pressing the left and right keys will make the ship turn, and pressing forward will make the ship moev in the direction it's turned.

I managed to get the ship to the way it's facing, but sideways.

The code of have for the ships movement is rather simple, hopefully the solution is equally simple.

What am I doing wrong? Why is the ship going sideways? Cheers.

float velocity = 5f;

double angle = 0;

Vector2 trajectory = new Vector2(velocity) * new Vector2((float)Math.Cos((double)angle,(float)Math.Sin((double)angle));

if (Keyboard.GetState().IsKeyDown(Keys.Up))
        {
            location += trajectory;   
        }

Upvotes: 0

Views: 573

Answers (2)

Andrew Russell
Andrew Russell

Reputation: 27245

Take a look at the wikipedia article for cartesian coordinates. And also Troigonometric functions (particularly the bits about unit circles).

To get a vector for an angle you use (as you have in your post) x = cos(angle) and y = sin(angle) (and don't forget that these methods take angles in radians, not degrees).

If you input an angle of 0 into that formula, you will have a trajectory that is traveling along the X axis. I'm guessing that your space-ship image is facing upwards? Hence the sideways movement.

The solution, of course, is to make your sprite point towards 0 degrees (ie: make it face right). Or, if you don't want to modify the image, add a fixed 90 degree offset to your angle before rotating, to compensate.

It gets a little more complicated than that - because XNA's SpriteBatch uses a client (not cartesian) coordinate system, where the Y axis is flipped (Y+ goes down, not up). So the rotation formula stays the same, it is still mathematically correct. But you might need to swap whether the left/right key increases/decreases your angle (because the Y axis is flipped, the meaning of angles also gets flipped).

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 882028

Not really much to go on, given the code you've shown, but I'd investigate two things.

First, your calculations may be okay but you may be drawing the ship sideways.

Second, your trig calculations may be swapped. Since sine and cosine are 90-degree phase-shifts of each other, getting them the wrong way around may well manifest itself as moving sideways. You need to ensure your calculations match your coordinate system.

Not really a definitive solution, more just some things to check but, as explained, you may get a better answer if you provide more detail.

Upvotes: 2

Related Questions