【问题标题】:How to measure mouse's travel distance?如何测量鼠标的移动距离?
【发布时间】:2017-02-07 22:53:28
【问题描述】:

我想为一个宠物项目测量鼠标的移动距离。所以我想设置一个实验:假设我能得到多精确的1m行进距离。

我尝试编写测试程序,但遇到了一些困难:屏幕边框。

我正在使用 Robot 类来设置鼠标即将到达边缘时的位置,但我不确定这是否正确。您知道如何解除屏幕绑定的任何技术或任何其他可行的解决方案吗?

这是我的测试代码:

public class App {
    public static void main( String[] args ) throws AWTException {
        Toolkit toolkit = new WToolkit();
        int screenResolution = toolkit.getScreenResolution();
        Robot robot = new Robot();
        List<Point> list = new ArrayList<Point>();
        int distance = 0;
        while (true) {
            if(MouseInfo.getPointerInfo().getLocation().y <= 50)
            {
                robot.mouseMove(910, 1080);
            }
            list.add(MouseInfo.getPointerInfo().getLocation().getLocation());
            if(list.size() >= 2) {
                Point p2 = list.get(list.size()-1);
                Point p1 = list.get(list.size()-2);
                if(p2.getY() <= p1.getY()) {
                    distance += (int) Math.sqrt(0 + Math.pow(p2.y - p1.y, 2));  // sqrt(pow(x2-x1) + pow(y2-y1))  sqrt(pow(x2-x1) = 0 for just measure on Y
                    System.out.println(distance / screenResolution * 0.0254);
                }
            }
            try {
                Thread.sleep(200);
            } catch ( Exception e) {
                System.out.println("something");
            }
        }
    }
}

【问题讨论】:

  • 是的,我想将鼠标的光学传感器用于机器人。使用传感器,我想测量机器人移动的距离。所以这就是为什么我想知道是否可以使用鼠标传感器。
  • 我认为你不能在 Java 中做到这一点。 MouseInfo 只能为您提供鼠标指针的当前位置 - 它无法测量超出您所在的 GraphicsDevice 的边缘。 (哎呀,我一开始在错误的框中输入了那个)。
  • 你为什么要平方然后平方根p2.y - p1.y
  • 这是因为距离公式:purplemath.com/modules/distform.htm我忽略了x,因为我只想在直线移动时检查它,所以x不会干扰结果。
  • 那么请查看Math.hypot

标签: java mouse awtrobot measurement


【解决方案1】:

在此解决方案中,您将不断更新点 p1 和 p2 以查找更新之间的总体移动距离

//I think this code should work for what you are doing
double distance = Math.sqrt(Math.pow(p1.getX()-p2.getX(),2)+Math.pow(p1.getY()-p2.getY(),2));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多