【问题标题】:How to get cardinal mouse direction from mouse coordinates如何从鼠标坐标中获取基本鼠标方向
【发布时间】:2010-12-13 22:45:33
【问题描述】:

是否可以根据鼠标最后位置和当前位置获取鼠标方向(左、右、上、下)?我已经编写了代码来计算两个向量之间的角度,但我不确定它是否正确。

有人可以指点我正确的方向吗?

    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);
    }

【问题讨论】:

  • 我什至会说角度方法不正确,句号。两个向量之间的角度差并不能告诉您该点移动的实际方向(在笛卡尔平面上)。
  • 您是否正在尝试适应鼠标抖动? - 例如,如果用户一直向右移动 100 像素,但在中途前后抖动了几个像素,你不想意外地对抖动进行采样并假设它们朝相反方向移动,因为整体图片没有得出这个结论
  • 不,我正在编写一个游戏,表单上的图像应该跟随鼠标的方向

标签: c# mouse position coordinates direction


【解决方案1】:

计算角度似乎过于复杂。为什么不做类似的事情:

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;

【讨论】:

    【解决方案2】:

    我认为您不需要计算角度。给定两个点 P1 和 P2,您可以检查是否 P2.x > P1.x 并且您知道它是向左还是向右。然后看 P2.y > P1.y 就知道是涨还是跌了。

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

    【讨论】:

      【解决方案3】:

      0,0 是左上角。如果当前 x > 最后 x,那么您将正确。 如果当前 y > last y,那么您将下降。如果您只对上\下、左\右感兴趣,则无需计算角度。

      【讨论】:

        【解决方案4】:

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

        您不必担心角度。

        【讨论】:

          猜你喜欢
          • 2011-06-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多