How to get cardinal mouse direction from mouse coordinates

Is it possible to get the direction of the mouse (left, right, top and bottom) based on the last position and current position of the mouse? I wrote code to calculate the angle between two vectors, but I'm not sure if it is correct.

Can someone point me in the right direction?

public enum Direction { Left = 0, Right = 1, Down = 2, Up = 3 } private int lastX; private int lastY; private Direction direction; private void Form1_MouseDown(object sender, MouseEventArgs e) { lastX = eX; lastY = eY; } private void Form1_MouseMove(object sender, MouseEventArgs e) { double angle = GetAngleBetweenVectors(lastX, lastY, eX, eY); System.Diagnostics.Debug.WriteLine(angle.ToString()); //The angle returns a range of values from -value 0 +value //How to get the direction from the angle? //if (angle > ??) // direction = Direction.Left; } private double GetAngleBetweenVectors(double Ax, double Ay, double Bx, double By) { double theta = Math.Atan2(Ay, Ax) - Math.Atan2(By, Bx); return Math.Round(theta * 180 / Math.PI); } 
+6
c # position coordinates mouse direction
source share
4 answers

Calculating the angle seems too complicated. Why not just do something like:

 int dx = eX - lastX; int dy = eY - lastY; if(Math.Abs(dx) > Math.Abs(dy)) direction = (dx > 0) ? Direction.Right : Direction.Left; else direction = (dy > 0) ? Direction.Down : Direction.Up; 
+12
source share

I don’t think you need to calculate the angle. Given the two points P1 and P2, you can check if P2.x> P1.x is there, 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 larger of the absolute delta values ​​between them, i.e. abs (P2.x - P1.x) and abs (P2.y - P1.y), and whichever is greater, tells you more horizontal " or β€œmore vertical,” and then you can decide if there was something that was UP-LEFT, UP or LEFT.

+5
source share

0,0 - upper left corner. If current x> last x, you go right. If the current y> last y, you are omitted. No need to calculate the angle if you are just interested in up / down, left / right.

+1
source share

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

You do not need to worry about corners.

0
source share

All Articles