Context
I'm working on making a variant of the atari game Breakaway IV and I'm trying to improve my mouse input handling.
I use the input of a mouse's motion left and right to move the bumper.
public void mouseLocationChanged(Point mouseLocation) {
if (lastMouseLocation == null) {
lastMouseLocation = mouseLocation;
return;
}
bumperStep = (int) ((mouseLocation.x - lastMouseLocation.x) * SENSITIVITY_MULTIPLIER);
lastMouseLocation = mouseLocation;
}
Then in the update method of my game I check if there is a bumper movement queued up.
public void update() {
if (inputHandler.isBumperMove()) {
submitBumperMove(inputHandler.getBumperMove());
}
...
}
If there is, I move the bumper with the below code.
public void submitBumperMove(int move) {
if (move < -1 * BUMPER_SPEED_LIMIT) {
move = -1 * BUMPER_SPEED_LIMIT;
} else if (move > BUMPER_SPEED_LIMIT) {
move = BUMPER_SPEED_LIMIT;
}
testPoint.x = bumper.x + move;
testPoint.y = bumper.y;
while (testPoint.x != bumper.x) {
if (!willCollideWithWall(bumper, testPoint)) {
bumper.x = bumper.x + move;
if (bumper.hasBall){
ball.x = ball.x + move;
}
} else {
move = shrinkStep(move);
testPoint.x = bumper.x + move;
}
}
}
Observed bugs
- I don't reset
bumperStep
with the call togetBumperMove()
so the cursor drifts if there isn't a different input to setbumperStep
to 0. This mainly happens when the mouse exits the window. - When resetting
bumperStep
to 0 withgetBumperMove()
(making itconsumeBumperMove()
) the mouse can run out of the window before the bumper reaches the edge of the game and the bumper can't be moved to the edge.
Proposed Solution
I was considering resetting the mouse cursor in the center of my window (with the cursor invisible) while the game is in "play" mode with each game update. This would prevent the problem of the mouse leaving the screen and not working while still allowing me to consume the movements which will stop the drifting bumper I'm observing.
Questions(finally ;-) )
- Is there a better approach to getting mouse left and right movements from any position in java, or should I stick with just keeping the cursor where I want it?
- If locking the cursor is the way to go, how can I pragmatically set the mouse position in Java? I've heard about a
Robot
class that is supposed to help, but it looked like an application needs special signing/permission to use that.