How can I perform 2D side-scroller collision checks in a tile-based map?

Posted by bill on Game Development See other posts from Game Development or by bill
Published on 2013-07-02T04:32:15Z Indexed on 2013/07/02 17:16 UTC
Read the original article Hit count: 338

Filed under:

I am trying to create a game where you have a player that can move horizontally and jump. It's kind of like Mario but it isn't a side scroller. I'm using a 2D array to implement a tile map.

My problem is that I don't understand how to check for collisions using this implementation. After spending about two weeks thinking about it, I've got two possible solutions, but both of them have some problems.

Let's say that my map is defined by the following tiles:

0 = sky
1 = player 
2 = ground

The data for the map itself might look like:

00000
10002
22022

For solution 1, I'd move the player (the 1) a complete tile and update the map directly. This make the collision easy because you can check if the player is touching the ground simply by looking at the tile directly below the player:

// x and y are the tile coordinates of the player. The tile origin is the upper-left.
if (grid[x][y+1] == 2){
   // The player is standing on top of a ground tile.
}

The problem with this approach is that the player moves in discrete tile steps, so the animation isn't smooth.

For solution 2, I thought about moving the player via pixel coordinates and not updating the tile map. This will make the animation much smoother because I have a smaller movement unit per frame. However, this means I can't really accurately store the player in the tile map because sometimes he would logically be between two tiles. But the bigger problem here is that I think the only way to check for collision is to use Java's intersection method, which means the player would need to be at least a single pixel "into" the ground to register collision, and that won't look good.

How can I solve this problem?

© Game Development or respective owner

Related posts about collision-detection