views:

353

answers:

4

Hello, is it possible to get the mouse direction (Left, Right, Up, Down) based on mouse last position and current position? I have written the code to calculate the angle between two vectors but I am not sure if it is right.

Can someone please point me to 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 = e.X;
        lastY = e.Y;
    }
    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        double angle = GetAngleBetweenVectors(lastX, lastY, e.X, e.Y);
        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);
    }
+9  A: 

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;
Aaron
thank you all for your help - this works fine
Ioannis
+4  A: 

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.

jeffamaphone
A: 

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.

McWafflestix
A: 

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.

asdfaaa