我在玩 slider 游戏时遇到问题,因为当我尝试快速撞击两个 block 时,碰撞代码会出现困惑。如果鼠标速度较慢,它会起作用。有没有办法对鼠标速度设置最大上限或更改我的代码以免发生这种情况?
//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);
}
}
最佳答案
我不会走上你试图限制鼠标速度的道路 - 用户有个人偏好。
您可以做的就是将用户交互与系统行为分开,以提高可靠性。保持并更新当前位置,并以指定的时间间隔在后台线程中计算碰撞 - 如果发生碰撞,则将用户移回原处。您应该能够以比用户注意到的更短的时间间隔运行它。您可以通过利用更多内核来提高性能,即 Java 7 ForkJoin 池是一个简单的解决方案。
关于java - 鼠标移动太快而无法检查碰撞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14426926/