是有可能得到鼠标方向(左,右,上,下),根据鼠标的最后一个位置和当前位置?我所编写的代码,以计算两个向量之间的角度,但我不知道这是否是正确的。

可有人请点我朝着正确的方向?

    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);
    }
有帮助吗?

解决方案

计算的角度看来过于复杂。为什么不这样做:

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;

其他提示

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

接着看,即ABS它们之间的增量的绝对值越大(P2.x - P1.x)和ABS(P2.y - P1.y),并以较高者为准告诉你,如果它是“更多的水平”或‘更垂直的’,然后你可以决定是否东西去UP-LEFT是向上或向左。

0,0是左上角。如果当前x>最后x,你会正确的。 如果当前y>最后Y,你会下降。没有必要,如果你在多达\只是感兴趣下,左\右计算角度。

粗略地讲,如果水平移动的大小(绝对值)(在X差异坐标)的最后的位置之间以及在当前位置大于的垂直移动的大小(绝对值)的情况下(沿Y差坐标)的最后位置和当前位置之间,则该移动被左或右;否则,它是涨还是跌。然后,所有你需要做的是检查运动方向的符号来告诉你,如果运动是向上或向下或左或右。

您不应该需要关注的角度。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top