My Pong game isn't working

Started by
3 comments, last by rip-off 12 years, 6 months ago
I have a ball Thread which checks to see if it has collided with anything, if it has collided with anything. If it has collided with the top or bottom walls it bounces in the opposite direction, if it has collided with the win trigger it calls my win() function. The problem I am having is in the collision detection with the paddles (kinda important =P). When it collides, instead of going in the opposite direction, it jumps around and goes quite spastic.

Heres my code:

public class Ball extends Thread{
int x = 100,y = (HEIGHT/2);
int xVel, yVel;

public void run(){
xVel = 10;
yVel = -14;
boolean win = false;
this.setPriority(10);


while(true){
try{
if(win == false){
x += xVel;
y += yVel;
}

if(ballRect != null){
if(ballRect.intersects(p1Win) || ballRect.intersects(p1Win)){
System.out.println("INTERSECT");
win = true;
if(ballRect.intersects(p1Win))
win("Player 1");
if(ballRect.intersects(p2Win))
win("Player 2");
break;
}

if(ballRect.intersects(p1Rect) || ballRect.intersects(p2Rect)){
xVel *= -1;
yVel *= -1;
if(ballRect.intersects(p1Rect))
x += 11;
else if(ballRect.intersects(p2Rect))
x -= 11;
System.out.println(xVel);
System.out.println(yVel);
System.out.println("INTERSECT IN PADDLE");
}
}

if(y <= 0 || y >= HEIGHT){
yVel *= -1;
System.out.println("Collision");
}



Thread.sleep(60);
repaint();
}catch(Exception e){
e.printStackTrace();
break;
}

}
System.out.println("BALL THREAD TERMINATED");

}
}



Any help would be greatly appreciated.
Advertisement
First of all you are checking p1win rect twice in the first if. Also in this case it doesn't effect speed much but in general it is not good to do if(op1 || op2) then if(op1) .. else if(op2) ...

For your question i'm not sure but it can be because of x+=11 and x-=11 operations. If it prints alot of "INTERSECT IN PADDLE" it is definitely because of them. Also since you know your paddle image's and ball image's width and height it is better to do like below (i assumed your origin is on the left side of images since it is default)


if(ball.intersect(pad1))
x = pad1.pos.x + pad.width + ball.width;

if(ball.intersect(pad2))
x = pad2.pos.x - ball.width;
By just a glance, don't flip the y velocity when hitting the paddle; you should only flip the x velocity. If the ball gets stuck in the paddle, you need to apply the new velocity to the ball's X right after flipping it:


xVel *= -1;
x += xVel;
Thanks, both you guys helped fix the problem. =D
Your Ball should not be a thread. You should not be using threads. I guarantee your code isn't safe, and you'll get some really weird bugs later on.

This topic is closed to new replies.

Advertisement