Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XNA 2D vector angles - what's the correct way to calculate?

what is in XNA in 2D the standard way vector angles work ?

0 degrees points right, 90 points up, 180 left, 270 down ?

What are the 'standard' implementations of

float VectortoAngle(Vector2 vec)

and

Vector2 AngleToVector(float angle)

so that VectortoAngle(AngleToVector(PI)) == PI ?

like image 693
Led Avatar asked Feb 16 '10 22:02

Led


People also ask

How do you find the angle of a vector in 2D?

To calculate the angle between two vectors in a 2D space: Find the dot product of the vectors. Divide the dot product by the magnitude of the first vector. Divide the resultant by the magnitude of the second vector.

How do you find the angle between three points?

The best way to deal with angle computation is to use atan2(y, x) that given a point x, y returns the angle from that point and the X+ axis in respect to the origin. double result = atan2(P3. y - P1. y, P3.


1 Answers

To answer your first question, 0 degrees points up, 90 degrees points right, 180 degrees points down, and 270 degrees points left. Here is a simple 2D XNA rotation tutorial to give you more information.

As for converting vectors to angles and back, I found a couple good implementations here:

Vector2 AngleToVector(float angle)
{
    return new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle));
}

float VectorToAngle(Vector2 vector)
{
    return (float)Math.Atan2(vector.Y, vector.X);
}

Also, if you're new to 2D programming, you may want to look into Torque X 2D, which provides a lot of this for you. If you've payed to develop for XNA you get the engine binaries for free, and there is a utility class which converts from angles to vectors and back, as well as other useful functions like this.

Edit: As Ranieri pointed out in the comments, that function doesn't make sense when up is 0 degrees. Here's one that does (up is (0, -1), right is (1, 0), down is (0, 1), left is (-1, 0):

Vector2 AngleToVector(float angle)
{
    return new Vector2((float)Math.Sin(angle), -(float)Math.Cos(angle));
}

float VectorToAngle(Vector2 vector)
{
    return (float)Math.Atan2(vector.X, -vector.Y);
}

I would also like to note that I've been using Torque for a while, and it uses 0 degrees for up, so that's where I got that part. Up meaning, in this case, draw the texture to the screen in the same way that it is in the file. So down would be drawing the texture upside down.

like image 88
Venesectrix Avatar answered Oct 18 '22 23:10

Venesectrix