atHorizontalEdge and atVerticalEdge can be declared inside or outside the while , which is not important.
It is important that the following calculation only once before the cycle begins:
atHorizontalEdge = (ball.getX() == getWidth() - BALL_SIZE) || ball.getX() == 0 ; atVerticalEdge = (ball.getY() == getHeight() - BALL_SIZE) || ball.getY() == 0 ;
Therefore, atHorizontalEdge and atVerticalEdge will have the same value from the beginning to the end of your run method (which is forever).
You obviously want these two lines to be executed at each iteration in your loop, since they will not be updated on their own ...
while (true) { atHorizontalEdge = (ball.getX() == getWidth() - BALL_SIZE) || ball.getX() == 0 ; atVerticalEdge = (ball.getY() == getHeight() - BALL_SIZE) || ball.getY() == 0 ; ... }
EDIT: Also, it would be better to check if x and y were greater than or equal to width / height and less than or equal to 0 for two reasons:
- If you decide to change the increment from 1, you can skip this exact value and cause an error, but more importantly:
- You are using
double , and the number of floating point numbers may differ from what you are comparing, therefore == may cause errors, and the ball may go past the edge and keep happening.
i.e. ball.getX() >= getWidth() ... ball.getX() <= 0
What Every Computer Scientist Should Know About Floating-Point Arithmetic
source share