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

有些话、适合烂在心里 提交于 2019-12-03 06:05:02

问题


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 ?


回答1:


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.




回答2:


There is no convention for which direction a certain angle represents in XNA, so you can just define it however you like.

I'm not sure when the last time I used angles in a game was. In almost every case it's easier to work directly with vectors, if a little less intuitive to begin with.



来源:https://stackoverflow.com/questions/2276855/xna-2d-vector-angles-whats-the-correct-way-to-calculate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!