javaanimationkeylistenerkeyeventbreakout

Java smooth movement with KeyEvents in breakout


I'm currently learning Java through Stanford's Programming Methodology (2008) course. I'm trying to create the game Breakout and am trying to currently animate the paddle, which is a GRect type object. Here's my code:

// moves paddle via keyboard
public void keyPressed(KeyEvent e) {
    int key = e.getKeyCode();
    if (key == KeyEvent.VK_RIGHT && paddle.getX() < getWidth() - paddle.getWidth()) {
        paddle.move(5, 0);
    }
    if (key == KeyEvent.VK_LEFT && paddle.getX() > 0) {
        paddle.move(-5, 0);
    }
}


//moves paddle via mouse
public void mouseMoved(MouseEvent e) {
    while (e.getX() > paddle.getX() + PADDLE_WIDTH/2 && paddle.getX() < getWidth() - PADDLE_WIDTH) {
        paddle.move(1, 0);
    }
    while (e.getX() < paddle.getX() + PADDLE_WIDTH/2 && paddle.getX() > 0) {
        paddle.move(-1, 0);
    }

The problem is, if I move the paddle with mouse, it follows just fine, it's much smoother than when I try to move it with keyboard. Changing the values in move() method only changes the speed at which the paddle moves.

I've tried googling and one of the things people do is to gradually increase and decrease the speed at which the paddle moves, but I'm not sure how to implement that correctly through this library. Here's my attempt:

private double acceleration(double finalSpeed) {
    if (finalSpeed > initialSpeed) {
        initialSpeed += delta;
    } else if (finalSpeed < initialSpeed) {
        initialSpeed -= delta;
    } 
    return initialSpeed;

}

private double initialSpeed = 0;
private double delta = 0.5;

After this I just set the paddle.move(acceleration(5),0) instead of paddle.move (5,0). And I've also added the KeyReleased method that sets the speed to the initial value:

public void keyReleased(KeyEvent e) {
    int key = e.getKeyCode();
    if (key == KeyEvent.VK_RIGHT || key == KeyEvent.VK_LEFT) {
        initialSpeed = 0;
    }

However, the movement of the paddle when I switch between left and right arrow keys is not responsive. It has about 0.5 sec delay to start moving the other direction, I've spend whole day trying to figure out the solution but to no avail. Please give me any tips, thanks!


Solution

  • It seems that there's some problem with the threads (which I don't fully understand). Doing this helped:

    Instead of moving the paddle directly with listeners, I created two booleans: left_key_downand right_key_down and set them to true if corresponding key was pressed. After that I moved the paddle using: if (left_key_down) move (-5,0) And similarly with right motion. This resulted in smooth motion.