Player not colliding with the walls correctly

47 views Asked by At
if(x>=Window.WIDTH-WIDTH/2)
{ 
    velX=-velX;
    x=Window.WIDTH-WIDTH;
    System.out.println("x: "+x);
    System.out.println("y: "+y);

}
if(x<0 + WIDTH/2||x<0-WIDTH/2){//good works
    x=0+WIDTH/2;
    velX=-velX;
    System.out.println("x: "+x);
    System.out.println("y: "+y);
}
else{
    x+=velX;
}
if(y>=Window.HIEGHT-HIEGHT){
    y=Window.HIEGHT-HIEGHT;
    velY=-velY;
    System.out.println("hit");
    System.out.println("x: "+x);
    System.out.println("y: "+y);
}
if(y<0 + HIEGHT/2){//good math works
    y=0+HIEGHT/2;velY=-velY;
    System.out.println("x: "+x);
    System.out.println("y: "+y);
}
else{y+=velY;}

The ball is supposed to collide with the walls of the the jframe but instead the one that control the out most x and y (ex 800 x 600) go in too far and the ones that control the beginning or x=0 or y=0 bounce to early. Can anybody tell me why?

1

There are 1 answers

9
Alex S. Diaz On

Assuming that x and y are the upper-left corner of the object sprite and WIDTH and HEIGHT its respectly dimension, you could try:

if(x >= Window.WIDTH - WIDTH || x <= 0) {
    velX = -velX;
    System.out.println("hit at: (x,y): " + x + "," + y);
} 
x+=velX;

if(y >= Window.HEIGHT - HEIGHT || y <= 0){
    velY = -velY;
    System.out.println("hit at: (x,y): " + x + "," + y);
}
y+=velY;

Let me know if it helps:)!