1

我在玩滑块游戏时遇到问题,因为当我尝试快速撞击两个方块时,碰撞代码会混乱。如果鼠标速度较慢,它可以工作。有没有办法对鼠标速度设置最大上限或更改我的代码以使其不会发生?

    //when the mouse is dragged and component selected is not null, continue
    if (componentName != null) {
        //get the current mouse x and y assuming that it was clicked from the middle of the component
        mouseX = e.getX() - carImage[Integer.parseInt(componentName)].getWidth() / 2;
        mouseY = e.getY() - carImage[Integer.parseInt(componentName)].getHeight() / 2;
        //get the direction of the selected component
        direction = group.get(mapsIndex)[Integer.parseInt(componentName)].updown(Integer.toString(Integer.parseInt(componentName)));
        //if the direction is horizontal, make sure that the object is not dragged off the screen (right and left)
        if (direction == true) {
            if (mouseX < 50) {
                mouseX = 50;
            } else if (mouseX > 50 * 7 - carImage[Integer.parseInt(componentName)].getWidth()) {
                mouseX = 50 * 7 - carImage[Integer.parseInt(componentName)].getWidth();
            }
            //get the location of the mouse for the y axis
            mouseY = carImage[Integer.parseInt(componentName)].getY();
            //if the direction is vertical, make sure that the object is not dragged off the top and bottom of the screen
        } else {
            if (mouseY < 50) {
                mouseY = 50;
            } else if (mouseY > 50 * 7 - carImage[Integer.parseInt(componentName)].getHeight()) {
                mouseY = 50 * 7 - carImage[Integer.parseInt(componentName)].getHeight();
            }
            //get the location of the mouse for the x axis
            mouseX = carImage[Integer.parseInt(componentName)].getX();
        }
        //find the area that the selected object occupies
        Rectangle or = carImage[Integer.parseInt(componentName)].getBounds();
        //go through all other components
        for (int x = 0; x < max; x++) {
            //as long as the comparison is not made with itself or a nonexistant object, continue
            if (x != Integer.parseInt(componentName) && carImage[x] != null) {
                //get the area that the compared object occupies
                Rectangle collide = carImage[x].getBounds();
                //if the two areas intersect, make the selected car go back to where it was
                if (or.intersects(collide)) {
                    mouseX = carImage[Integer.parseInt(componentName)].getX();
                    mouseY = carImage[Integer.parseInt(componentName)].getY();
                }
            }
        }

        //update the component's location to where the mouse is
        carImage[Integer.parseInt(componentName)].setLocation(mouseX, mouseY);
    }
}
4

1 回答 1

1

我不会走你试图限制鼠标速度的道路——用户有个人偏好。

您可以做的是将用户交互与系统行为分开以提高可靠性。保持并更新当前位置并以指定的时间间隔在后台线程中计算碰撞 - 如果发生碰撞,则将用户移回。您应该能够以比用户注意到的更短的时间间隔运行它。并且您可以通过利用更多内核来提高性能,即 Java 7 ForkJoin 池是一个简单的解决方案。

于 2013-01-20T17:07:54.427 回答