Sign in to follow this  
spacekid434

My Pong game isn't working

Recommended Posts

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:

[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");

}
}[/code]


Any help would be greatly appreciated.

Share this post


Link to post
Share on other sites
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)

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

if(ball.intersect(pad2))
x = pad2.pos.x - ball.width;
[/code]

Share this post


Link to post
Share on other sites
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:

[code]
xVel *= -1;
x += xVel;
[/code]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this