如何从鼠标坐标获取基数鼠标方向

时间:2009-11-06 18:23:50

标签: c# mouse position coordinates 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);
    }

4 个答案:

答案 0 :(得分:12)

计算角度似乎过于复杂。为什么不这样做:

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;

答案 1 :(得分:5)

我认为你不需要计算角度。给定两点P1和P2,您可以检查P2.x> P1.x,你知道它是向左还是向右。然后看看P2.y> P1.y,你知道它是上升还是下降。

然后查看它们之间的差值的绝对值中的较大者,即abs(P2.x - P1.x)和abs(P2.y - P1.y),以较大者为准告诉您它是否为“更多水平“或”更垂直“然后你可以决定向上或向下的东西是向上还是向左。

答案 2 :(得分:1)

0,0是左上角。如果当前x>最后x,你说得对。 如果当前y>去年,你要走了。如果您只对up \ down,left \ right感兴趣,则无需计算角度。

答案 3 :(得分:0)

粗略地说,如果最后位置和当前位置之间的水平移动的幅度(绝对值)(X坐标的差)大于垂直移动的幅度(绝对值)(Y坐标的差)在最后位置和当前位置之间,然后左右移动;否则,它是向上还是向下。然后你要做的就是检查运动方向的标志,告诉你运动是向上还是向下或向左或向右。

你不应该担心角度。