Your if
statement does not correctly handle conditions where the ball is exactly at boundaries between conditions. You have:
if (ball.getY() < getHeight()-HEIGHT/2 && ball.getY() > HEIGHT/2) {
...
} else if (ball.getY() < HEIGHT/2) {
...
} else {
...
}
But what happens when ball.getY() == HEIGHT/2
? In this case, it will fall through to the third block, but this is not the desired behavior - it will briefly jump to the third condition when ball.getY() == HEIGHT/2
, hence flicker when the ball's Y position is at that edge. Instead, make a simple change to your second condition:
if (ball.getY() < getHeight()-HEIGHT/2 && ball.getY() > HEIGHT/2) {
...
} else if (ball.getY() <= HEIGHT/2) { // note <= instead of <
...
} else { // ball.getY() >= getHeight()-HEIGHT/2
...
}
This should take care of the transition cases.
By the way, unrelated, you should use curly braces in nested if
statements like the one you have, e.g.:
if (bool) {
if (dx > 0)
dx += 1;
else
dx -= 1;
} else {
if (dy > 0)
dy += 0.5;
else
dy -= 0.5;
}
While your original logic happens to have the same effect in this case, your original code, despite its slightly misleading indentation, actually had this structure:
if (bool)
...
else if (dy > 0)
...
else // !bool && dy <= 0
...
That probably doesn't reflect the actual intent of that if
and, even though it happens to work here, adding the curly braces is a good habit to get into because it can prevent potential subtle logic errors in more complex code.