• Advertisement
Sign in to follow this  

Tile map based collision detection question

This topic is 3351 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

hey guys, i'm reasonably new to SDL and i can program in C++ at an intermediate level (i guess) I've recently started toying with the idea of a 2d game, so i did the usual tutorials to get started with moving a sprite character on screen etc, then i came across a tiling tutorial; which i attempted and completed. my question is this: how can i have collision detection for when my character hits a certain tile? for example: I have a sprite which moves around the screen, and i have a 2D array of integers, which map grass(0) and cobblestones(1), these are blitted to the screen using 2 nested for loops for X and Y. But how can i detect a collision from the sprite to a co-ordinate within this 2D array, so that the cobbles can't be touched. I have full source code if anyone would like to see. cheers, awesome website here. Ollie.

Share this post


Link to post
Share on other sites
Advertisement
An easy way would be to use your characters x and y coordinates and turning them into an index in the array. I'll explain what I mean.

Lets say that every tile is 32x32 so if your character was at an X position of 64 and a y position of 32 then he would have the index of [2,1] in the array. You would get this position by dividing the x and y coordinates of your character by the size of the tile.

Then you could have a method to check if the spot your character will be moving to is a spot that doesn't have the value of 1. So you check for the key press and then before you move your character check the spot in the array that the character will move for a value. If that value doesn't equal one then you can move there.

Does that make sense?

Share this post


Link to post
Share on other sites
you sir, are an absolute genious.

Is this the way that collision detection is generally achieved in tile based games then?

Ollie.

Share this post


Link to post
Share on other sites
That's one way, a very simple one which would work when the movement is based on tiles rather than pixel distance, it would work for say chess, or a similar game where tiles are part of the gameplay itself, for something like Super Mario, you would need something more complex, like in the Metanet Tutorials (A B), or at least use bounding boxes in order to determine how much the sprite may advance before hitting face first a wall.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement