# Collision Detection in Java for a game

Im making a game in Java with a few other people but we are stuck on one part of it, making the collision detection. The game is an RPG and I know how to do the collision detection with the characters using Rectangles, but what I dont know how to do is the collision detection for the maps. What I mean by that is like so the character cant walk over trees or water and that stuff but using rectangles doesnt seem like the best option here.

Well to explain what the game maps are gonna look like, here is an example:

Now I could use rectangles to get bounds and stop the player from walking over the trees and water but that would take a lot of them.

But is there another easier way to prevent the player from walking over the trees and obstacles besides using Rectangles?

Your map looks like a 2D grid so why not have a boolean[][] lookup table for the map? Or even int[][] if you want different grid cell types. For smoothing movement around corners you can look up the target position and make a smoother animation, e.g.

if (movingUpRight && myGrid[playerPosX + 1][playerPosY + 1] == TILE_EMPTY) { /* smooth animation */}

Judging by your question you don't need anything more complicated than that.

If you do need something more fancy take a look at Recast/Detour project [1][2] but it doesn't seem to have a Java binding or port (apart from CritterAI but it's not a straight port) so far but someone's got to do the work sooner or later :) If you choose to go that route please get in touch as I plan to support it in my game at some point so we can coordinate the efforts.

• This is a very performant solution. Looking up to see if a tile walkable is basically O(1) – Nick Van Brunt Mar 7 '11 at 16:36

You use something called a nav mesh. This is basically (in this simple case) a texture with just one bit for each square- collidable or not. When the player tries to move, you check the texture.