I am making the game Breakout in Java and I have one slight problem:
if(ballLocation.y >= 430){ //baseline
if((ballLocation.x >= batLocation.x) && (ballLocation.x <= (batLocation.x + width))){ //determining whether or not the ball is touching the bat by establishing a range of values
directionY = -2; //changing the direction of the ball so that it appears to be bouncing off when it hits the bat
}
}
If I hit the ball on the bat further to the left the if statement is true, however for some reason if it hits further to the right it is false even though I can see that the ball is hitting the bat. So I think that the only problem can be with adding the width
variable to the batLocation.x
, because batLocation.x
is in terms of units on the x
axis, and the width
is the width of the image (as the bat and ball are both png files and not just drawn by the game) in terms of pixels (which is 10
).
So I am thinking that the most likely reason why my code is not working is because I am making a false assumption and assuming that if I add the width in pixels to the starting x
point that I will get the length of the bat when perhaps 1 pixel is not equal to 1 unit on the x
axis.
So is this the case? Is 1 pixel not equal to one unit in terms of the x or y axes? And if it is not, then how many units in terms of x
is my bat's width if it is 10 pixels in width?
I have got the latest version of JDK 8.
There isn't really a built-in x and y axis, except when you draw, and that's always in pixels. What units have you made x and y in? When you draw, do you use those values as the screen location? If so, try RealSkeptic's suggestion; otherwise, the units are however you defined them.