I made this rectangle collision system for a simple game I'm working on, but it's not working properly. It only registers a collision when the bottom left pixel of the player collides with the object, and I can't figure out why. Thanks in advance for any help.
public static boolean collision(int playerX, int playerY, int playerWidth, int playerHeight,
int obstacleX, int obstacleY, int obstacleWidth, int obstacleHeight){
if (coordinateWithinRect(playerX, playerY, obstacleX,
obstacleY, obstacleWidth, obstacleHeight)) {
return true;
} else if (coordinateWithinRect(playerX - playerWidth,
playerY, obstacleX, obstacleY, obstacleWidth,
obstacleHeight)) {
return true;
} else if (coordinateWithinRect(playerX - playerWidth,
playerY + playerHeight, obstacleX, obstacleY,
obstacleWidth, obstacleHeight)) {
return true;
} else if (coordinateWithinRect(playerX, playerY
+ playerHeight, obstacleX, obstacleY, obstacleWidth,
obstacleHeight)) {
return true;
} else {
return false;
}
}
private static boolean coordinateWithinRect(int xCoord, int yCoord, int xRect, int yRect, int width, int height) {
if (xCoord > xRect && xCoord < (xRect + width) && yCoord < yRect && yCoord > (yRect - height)) {
return true;
} else {
return false;
}
}
In your function
coordinateWithinRect
you specify a width and height for your obstacle but not for your player. Is this intentional, I mean your player does not have any dimensions or they are not considered important?Anyway, judging by the general idea of your definition of collision, I guess player is considered to collide with obstacle when it's inside the rectangle of obstacle, right? So, you should check if
playerX
is insideobstacleX-obstacleWidth/2
andobstacleX+obstacleWidth/2
whileplayerY
is insideobstacleY-obstacleHeight/2
andobstacleY+obstacleHeight/2
at the same time.Your function should be:
You don't make these checks so sure you have something wrong here or am I missing something?