I am trying to learn about programming 3D in javafx. My goal is to lock the cursor in the center or move it to the center for a first person view.
I made a mouse moved event and I move the cursor to the middle of the screen, then change the camera depending on where I moved the mouse to. The problem is that whenever it moves the cursor back to the center the event fires again reversing the change in camera angle. Anyone know a way to make it so when it moves the cursor back to the center it doesn't affect the camera angle?
scene.setOnMouseMoved(e -> {
int screenWidth = (int) Screen.getPrimary().getBounds().getWidth();
int screenHeight = (int) Screen.getPrimary().getBounds().getHeight();
moveCursor(screenWidth / 2, screenHeight / 2);
double dx = mouseX - e.getSceneX();
double dy = mouseY - e.getSceneY();
mouseX = e.getSceneX();
mouseY = e.getSceneY();
camAngleX += dx / 10;
camAngleY -= dy / 10;
});
Here is after adding the Boolean check... I defined "ignoreMouseMove" somewhere else.
scene.setOnMouseMoved(e -> {
if (ignoreMouseMove) {
ignoreMouseMove = false;
} else {
double cx = primaryStage.getX() + scene.getX() + sceneX / 2;
double cy = primaryStage.getY() + scene.getY() + sceneY / 2;
double dx = mouseX - e.getSceneX();
double dy = mouseY - e.getSceneY();
mouseX = e.getSceneX();
mouseY = e.getSceneY();
camAngleX += dx / 10;
camAngleY -= dy / 10;
ignoreMouseMove = true;
moveMouse(cx, cy);
}
}
1 Answer 1
You just need a boolean check like:
boolean ignoreMouseMove = false;
scene.setOnMouseMoved(e -> {
if(ignoreMouseMove) {
ignoreMouseMove = false;
} else {
int screenWidth = (int) Screen.getPrimary().getBounds().getWidth();
int screenHeight = (int) Screen.getPrimary().getBounds().getHeight();
ignoreMouseMove = true;
moveCursor(screenWidth / 2, screenHeight / 2);
double dx = mouseX - e.getSceneX();
double dy = mouseY - e.getSceneY();
mouseX = e.getSceneX();
mouseY = e.getSceneY();
camAngleX += dx / 10;
camAngleY -= dy / 10;
}
});
If it helps you here is an implementation I did myself a few weeks back that works:
Robot mouseMover = new Robot(); //defined somewhere else
scene.setOnMouseMoved(event -> {
if(ignoreMouseEvent) {
ignoreMouseEvent = false;
return;
}
mouseDeltaX += Math.round(event.getScreenX() - (stage.getX() + (stage.getWidth() / 2.0))) / 5.0;
mouseDeltaY += -Math.round((event.getScreenY() - (stage.getY() + (stage.getHeight() / 2.0)))) / 5.0;
ignoreMouseEvent = true;
mouseMover.mouseMove((int) (stage.getX() + (stage.getWidth() / 2.0)), (int) (stage.getY() + (stage.getHeight() / 2.0)));
});