trying to make a table tennis game. simple one with two paddles and one ball.
so i have two paddel which is a long rectenger. and a ball.
ball i have set


this code above will let the ball keep on going right and down. if ball hit top of screen or bottom of screen than i am just change the direction by

dy = -dy

now i want to set collision between ball and paddle

x = ball x
y = ball y postion
dy = -dy // change ball postion
dx = -dx //change ball postion
radius = ball radius
py1 //paddle y postion
px1 //paddle x postion

this code below should work but some thing is wrong. it never go in System.out.println("hi");
1st if statment check if so ball cant go right side of paddle
2nd if statment check ball is middle of paddle
now it means ball has hit the paddle than change direction of ball

if(x+radius < px1+pw1 && x+radius > px1)

            if(py1+ph1 > y+radius && py1 < y+radius)
                dy = -dy;
                dx = -dx;   


any idea whats wrong with my logic?

try adding some print statements to check what the values of those variables are. if the expression never returns true, then it's pretty normal it never prints "hi".

Since the paddle is a shape with plenty of area, we need more information on the py1/px1 positions, is it the direct center, top or bottom? Assuming by your code it's the bottom.

This may not solve your problem, but a slight tweak on the if statements.

if(y-radius <= (py1+ph1) && y+radius >= py1) {
    if(x+radius >= px1 && x+radius <= (px1+pw1)) {


    }//if ball hits, x axis
}//if ball hits, y axis

This change also lets the ball have a symmetrical hit box on the top of the paddle and the bottom.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.