[C++/SDL] Tile-Based Collision Detection

Hi guys

I'm still working on my Project and the next Problem has occured: How do I detect collisions on a tilebased map? My tiles are 16x16 and the map is based on the tutorial of sdltutorials.com (http://www.sdltutorials.com/sdl-maps). I really like this Approach because I can define for each tile of what type it should be (so a earth tile can be walkable and lead to a secret passage).
The first Number stands for what Kind of tile it should be (e.g. Grass, Earth, Water, Blank,...) and the number after ":" stands for the type of the tile (e.g. solid, walkable, do dmg to the Player,...).

e.g.
0:0 0:0 0:0 0:0 0:0 //No tile and walkable
0:0 0:0 0:0 0:0 0:0
0:0 0:0 0:0 0:0 0:0
1:1 1:1 1:1 1:1 1:1 //Grass tile and solid
2:1 2:1 2:1 2:1 2:1 //Earth tile and solid

It's working just fine with loading the Images, but i've got no clue about the collision.
I've already read a lot of stuff on the Internet but I don't get how to Combine it the structure from above. For example lazyfoo describes the collision with one object like one wall. So how can I check the Player Position with each tile?

Do you even have some better ways of doing this? For now there's no camera, but I plan to implement one later...

Thx for your suggestions

Half_NOoB

(EDIT: I'm trying to make a 2D platformer...)
Last edited on
If you can get the players position, then you could move around in the file to find the tile that the player is on.
In my CPlayer-class is the x/y-position of the Player in a member variable stored.

int m_PosX;
int m_PosY;

Would you mind going a Little bit more into Detail with your Suggestion?
You might want to look at using fseek to move around in the file. if you've got the width of the file, you could make a function that gets the text at x and y positions in text files.
psuedo-code
1
2
3
4
5
6
string xyFile(int x, int y,int width, FILE file) {
     string f;
     fseek(width*y+x, file);
     fscanf (file, "%f", &f);
     return f;
}
Last edited on
Hm i don't understand what you're trying to say...


I've come up with something to get the Playerposition in relation to the tile in the meanwhile:

1
2
3
int TileX = Player.GetPosX() / TILE_SIZE; //--> If the Player X-Coordinate is 320, TileX would be 20
int TileY = Player.GetPosY() / TILE_SIZE; //--> If the Player Y-Coordinate is 160, TileY would be 10


But how can I tell the Computer with which tile he should check for collision?
If you move left then check TileX - 1, TileY

If you move down then check TileX, TileY + 1

etc

Check before moving and move only if the tile is walkable.
Topic archived. No new replies allowed.