I'm building a top-down 2D scroller using java swing with very similar gameplay to that of the classic game Bomberman, where the player can move the character in all 4 cardinal directions.
All the game objects have instance variables containing the (x,y) coordinates of where they are to be rendered on the JPanel, they also have instance variables for the previous (x,y) coordinate where they were rendered in the last frame. My collision detection algorithm essentially checks to see if the player object intersects one of the walls present in the grid every time we refresh the screen - This can be seen in the bit of code below:
if (playerRectangle.intersects(wallRectangle)) {
player.restorePreviousPosition();
}
The restorePreviousPosition() method sets the (x,y) coordinates of the player to what they were before the collision occurred. This methods works fine, it prevents the player from going through objects. However, the controls seem very jagged because if the player is, for example, trying to move left and up while in contact with a wall, the character remains still. In other words, the character can't touch a wall and still move parallel to it. In order to fix this problem I created four rectangles drawn on top of the player object that I use to determine the side that is colliding with another object, so that instead of restoring the (x,y) coordinates I can restore x or y depending on which side is colliding. For example, if I know that the top is colliding with something, then I can restore the y position and allow the x to change freely. Below you can see a picture of the player object with the rectangles drawn on it:
This idea is very unreliable, specially in corners where it is difficult to determine from which side the collision is coming from. So, my question is, how can I reliably determine which side of a rectangle is colliding with another rectangle in java using swing? Or, do you have a better alternative to my approach towards detecting collisions?
Note that player movement is completely free, my implementation doesn't snap the character from tile to tile. And that the distance between tiles is 32x32 pixels, and the player is 30x30 pixels.
Thank you for the help. If you have any extra questions about my implementation, please let me know.