How to get cardinal mouse direction from mouse coordinates

故事扮演 提交于 2019-12-01 17:23:35

Computing the angle seems overly complex. Why not just do something like:

int dx = e.X - lastX;
int dy = e.Y - lastY;
if(Math.Abs(dx) > Math.Abs(dy))
  direction = (dx > 0) ? Direction.Right : Direction.Left;
else
  direction = (dy > 0) ? Direction.Down : Direction.Up;

I don't think you need to calculate the angle. Given two points P1 and P2, you can check to see if P2.x > P1.x and you know if it went left or right. Then look at P2.y > P1.y and you know if it went up or down.

Then look at the greater of the absolute values of the delta between them, i.e. abs(P2.x - P1.x) and abs(P2.y - P1.y) and whichever is greater tells you if it was "more horizontal" or "more vertical" and then you can decide if something that went UP-LEFT was UP or LEFT.

0,0 is the top left corner. If current x > last x, you're going right. If current y > last y, you're going down. No need to calculate the angle if you're just interested in up\down, left\right.

Roughly speaking, if the magnitude (absolute value) of the horizontal move (difference in X coordinates) between the last position and the current position is greater than the magnitude (absolute value) of the vertical move (difference in Y coordinates) between the last position and current position, then the movement is left or right; otherwise, it is up or down. Then all you have to do is check the sign of the movement direction to tell you if the movement is up or down or left or right.

You shouldn't need to be concerned about angles.

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