Intersects() works just first time
Hello every1! :)
I'm coding a Ping Pong game. It's almost over, but if player lost round his paddle is doing strange things... If I win there's everything alright.
Please, watch video: stackoverflow - Dailymotion Wideo You see left paddle after MsgBox (0:18+)? I don't know what is causing that behavior. IMO the code is fine.
Method responsible for intersection:
Code:
Runnable r1 = new Runnable() {
public void run() {
try {
while (true) {
board.pPaddle.setBounds(board.p.getX(), board.p.getY(), 10, 50);
board.aiPaddle.setBounds(board.a.getX(), board.a.getY(), 10, 50);
board.ball.setBounds(board.b.getX(), board.b.getY(), 10, 10);
if (getY() < 1) { //ceiling
y = 2;
speedY = 1.11 + local.nextDouble() + 0.11;
} else if (getY() > 261) { //floor
speedY = -speedY;
}
if (board.ball.intersects(board.pPaddle)) { //ball intersects player's paddle
direct = local.nextInt(3);
if (direct > 1) {
speedY = local.nextInt(3) + 0.11
+ local.nextDouble();
} else {
speedY = -local.nextInt(3) + local.nextDouble();
}
speedY = local.nextInt(3) + 0.11;
speed = -speed;
} else if (board.ball.intersects(board.aiPaddle)) { //ball intersects computer's paddle
direct = local.nextInt(3);
if (direct > 1) {
speedY = local.nextInt(3) + 0.11
+ local.nextDouble();
} else {
speedY = -local.nextInt(3) + local.nextDouble();
}
speed = -speed;
speedY = -speedY;
}
x += speed;
y += speedY;
board.repaint();
Thread.sleep(10L);
board.checkWin();
}
}catch(InterruptedException e){
}
}
};
}
If you need more code, just write. :)
Regards,
Adrian
Re: Intersects() works just first time
Quote:
Originally Posted by
Szinek
...IMO the code is fine.
Whenever I see this, I know for a fact that the code is not fine. Trust me, you've got a bug in your code, not in Java itself. The problem is finding the bug. Consider using a debugger or println statements or a logger to see what the state of your variables are at various points in your program.
I do see things that worry me, mainly that you're making GUI calls off of the event thread, and this can cause strange bugs. But otherwise your first order of business is to identify the error, and that's going to take effort you your part. Find out what changes in the program's state if the player loses as that would be a good place to start.
Re: Intersects() works just first time
Now I know what's happening. After first lost round speeds are going mad, just for the first collision.
Quote:
java.awt.Rectangle[x=4,y=190,width=10,height=50] X4 Y190 speedY 0.11 speedX 1.5
java.awt.Rectangle[x=4,y=190,width=10,height=50] X4 Y190 speedY -0.89 speedX -1.5
java.awt.Rectangle[x=4,y=190,width=10,height=50] X4 Y190 speedY -1.89 speedX 1.5
java.awt.Rectangle[x=4,y=190,width=10,height=50] X4 Y190 speedY -0.89 speedX -1.5
I'm trying to figure it out, thanks, Fubarable.
No idea :/