LJay
LJay

Reputation: 11

Breakout game Java - paddle going off right side of screen

i've got an issue with my breakout game in java. Everything works well other than my paddle going off the screen on the right side, my ball does this too, but not worried about that right now.

// prevent paddle from moving outside of the screen

Public void update() { x += xVelocity;

if (x <= 0) {
setX(0);
xVelocity = -1;

}
if (x >= 
(Settings.WINDOW_WIDTH 
- Settings.PADDLE_WIDTH) {
setX(Settings.WINDOW_HEIGHT 
- Settings.PADDLE_HEIGHT); 
xVelocity = 1;
}

// set velocity depending on pressing left or right

Public void keyPressed(KeyEvent e)

if (e.getKeyCode() == 
KeyEvent.VK_LEFT) {

paddle.setXVelocity(-1);

} else if (e.getKeyCode() == 
KeyEvent.VK_RIGHT) {

paddle.setXVelocity(1);
}
}

// set velocity after keys released

Public void keyReleased(KeyEvent e) if (e.getKeyCode() == KeyEvent.VK_LEFT) {

paddle.setXVelocity(0);

} else if (e.getKeyCode() == 
KeyEvent.VK_RIGHT) {

paddle.setXVelocity(0); 
}
}

How do i get the paddle to 
stay on screen on the right 
side? 

Any help appreciated

Upvotes: 0

Views: 213

Answers (1)

dhakalkumar
dhakalkumar

Reputation: 191

Change this

if (x <= 0) {
    setX(0);
    xVelocity = -1;
}
if (x >= 
(Settings.WINDOW_WIDTH 
- Settings.PADDLE_WIDTH) {
setX(Settings.WINDOW_HEIGHT 
- Settings.PADDLE_HEIGHT); 
xVelocity = 1;
}

to this

if (x <= 0) {
    setX(0);
    xVelocity = -1;
}
if (x >= (Settings.WINDOW_WIDTH - Settings.PADDLE_WIDTH) {
    setX(Settings.WINDOW_WIDTH - Settings.PADDLE_WIDTH); 
    xVelocity = 1;
}

When you check if the value of x is within the difference of window width and paddle width, the new value of x should be set as the difference of window width and paddle width, NOT the difference between window height and paddle height.

Upvotes: 0

Related Questions