Benjamin Kovach
Benjamin Kovach

Reputation: 3260

Vector movement with respect to rotation

Say I have a vector (x,y) and it is aligned to the origin by a rotation (say, pointing 30 degrees up).

If I want to move that vector one unit with respect to the direction (so, one unit forward facing 30 degrees up), how would I go about doing so?

I'm working on putting a simple third-person game together and I would like to be able to rotate the character and move it forward regardless of rotation, and I'm kind of lost as to how to do this.

EDIT:

After this question was answered, I went ahead and figured out how to get a backwards, left, and right movement, so I figured I'd stick this in here for reference if anyone needs help.

Given Gunther2's code, To get a backwards motion, simply subtract the displacement from the current position:

position -= displacement;

To get a left motion, change the displacement variables to

displacement.x = (float)Math.Sin(angle + PI/2); 
displacement.y = (float)Math.Cos(angle + PI/2);

Replace PI/2 with 90 if Sin/Cos accepts degrees instead of radians.

Then subtract displacement:

position -= displacement;

To get a right motion, simply follow the same steps but add the new displacement:

position += displacement;

Upvotes: 4

Views: 3637

Answers (1)

Foggzie
Foggzie

Reputation: 9821

First you would need a vector representing the angle:

Vector2 displacement;
displacement.x = (float)Math.Sin(angle);
displacement.y = (float)Math.Cos(angle);

Then, since the length of this vector (x,y) will always be 1, you multiply it by how far you're traveling. If you want to travel a distance of 1, then X and Y are already the size they need to be.

displacement *= speed;  // Assuming your Vector2 *= operator supports a scalar

Add the displacement to the current position:

position += displacement;

Upvotes: 4

Related Questions