# dont understand how to test 2d collision in java

## Recommended Posts

I have been working on this simple pong game for a few days and I still cant seem to be able too test for collision acurately or to even get it to work ... heres what I have so far...(note that this is only for the right side of the player)
	private void doCollisionTest(ComPaddle com, Player player){
int playerleft = player.getSide();
int playerwidth = player.getWidth();
if (playerleft>250){playerwidth=-playerwidth;}
int playerright = playerleft+playerwidth;
int playertop = player.getYPos();
int playerbottom = playertop + player.getheight();
if(ballx_speed<0){//check if ball is traveling to left if it is
if(ballleft<=playerright){//check if player and ball are on same y axis
for(int playerheightseed=0; playerheightseed<player.getheight();playerheightseed++){//start seed to get all of player height on x axis
for(int ballheightseed=0;ballheightseed<ball_radius*2;ballheightseed++){//start seed to get all of ball height on x axis
if(balltop-ballheightseed==playertop-playerheightseed){//check to see of ball and player are overlapping at x axis
this.ballx_speed = -ballx_speed;
}
}
}
}
}

}


[Edited by - jpetrie on February 11, 2010 5:33:05 PM]

##### Share on other sites
it seems to never check collision on the y axis only on the x

##### Share on other sites
I think you might be over complicating things.

private final int leftCollision = 0, rightCollision = 640;//returns true if a collision is detectedpublic boolean checkCollision() {    if ((ballX - ballRadius) <= leftCollision) { //check for collision on left        if ( ((ballY - ballRadius) <= (paddleY + paddleHeight)) && ((ballY + ballRadius) >= (paddleY - paddleHeight)) ) {	    return(true);	}    } else if ((ballX + ballRadius) >= rightCollision) { //check for collision on right	//same thing as above but for the other paddle    }    return(false);}

##### Share on other sites
yeah but when i do it like that doesnt it only check it for 2 points on the object...with the loop it checks each pixel or am i wrong..it seems that if a loop isnt used and the ball has a slop of 0 it is very unlikely a collision will be detected...

##### Share on other sites
The method I posted is 100% accurate when your working with a rectangle and a circle. Draw a rectangle in Paint and then draw a circle and move it around to visualize and confirm for yourself.

##### Share on other sites
ok great thanks i found some time to test it and it works thank-you

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628375
• Total Posts
2982310

• 10
• 9
• 14
• 24
• 11