Vector math, finding the angle

纵然是瞬间 提交于 2019-12-14 02:16:15

问题


I am trying to learn XNA by writing a small 2D game, it's a Top-Down perspective and Im trying to have double movement, moving along the axis using Left-Right and Up-Down keys, as well as looking right at the mouse cursor, so that the player can run and aim at the same time.

I have one vector for the player position (m_PlayerPos), and one vector for the mouse position (m_MousePos), and im trying to get the correct angle towards the mouse position.

Im using the formula method:

public static float Angle(Vector2 from, Vector2 to)
{
    return (float)Math.Atan2(from.X - to.X, from.Y - to.Y);
}

This works, but for some reason the method only works half-way, along the x-axis. When the mouse is to the exact left of right of the player, the player looks right at the mouse.

But if I move to the top of the player, it looks down, and if the mouse is below the player, the player looks up. So I need to inverse the Y axis, but Im not sure how.

Thanks in advance for any feedback.


回答1:


Use to.Y - from.Y.




回答2:


Multiply it with (0.0, -1.0) (or just multiply the Y component by -1.0). This will mirror the vector along the horizontal axis and should achieve the result you want.




回答3:


In screen space the origin is in the top-left corner with the Y axis pointing downward whereas in eucledean space the Y axis points upwards. That's why you observe the Y axis being "flipped".



来源:https://stackoverflow.com/questions/4428365/vector-math-finding-the-angle

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