In my game i have a 2D int array walls[][], where i store the information about the Tiles. For me 0 is no wall, so i can go throught. All other numbers repressent some special walltypes, wtih which i have to handle collisions. To detect if a collision happens i do something like this:
if (yMov > 0) {
int leftX = (int)(position.x - width/2); // The leftmost point of the Object.
int rightX = (int)(position.x + width/2); // The rightmost point of the Object.
int newMaxY = (int)((position.y * yMov * currentSpeed * delta) + height/2);
if (walls[leftX][newMaxY] != 0 || walls[rightX][newMaxY] != 0)
// Collision in positive y-Direction.
Notes:
- This is presolve, so detect collision first and then move. For this you have to store the result of the collision detection somewhere.
- The Tiles, in which the character is, are defined by the
Integer presentation of their position.x and position.y.
yMov describes the percntual value of the movement in y-Direction. So if you go 45° to the right, up you have yMov = 0.5, xMov = 0.5. Left up would be yMov = 0.5, xMov = -0.5.
- Use this example code block up there and copy it 3 times, for
yMov < 0, xMov > 0, xMov < 0.
- The position in this example is the middle of the object. If in your case it is the left lower corner you just need to add full height for up-movement, full width for right-movement and no height/ width for the other movements.
EDIT: I try to explain it better: You have a Sprite defined by his center point:position.x,position.y and his size: size.x, size.y (width and height).
Now think about the case, you run to the right. In this case you can never collide with a tile at your left side. Also if you are moving to the right you can not collide with tiles above or under you. So there is only 1 Tile to check: The Tile to your right. Also you can only collide with the Tile to your right, if the right part of your sprite (position.x + size / 2) moves far enought.
In case you are moving in between 2 tiles in y direction you have to check the Tile at your newX postition and your upperY (position.y + size.y / 2) and lowerY (position.y - size.y / 2).
To give you a picture of what i am using: Collision detection. Look at the 3rd picture, with this description:
The above image gives us 2 candidate cells (tiles) to check if the objects in those cells collide with Bob.
This collision there is for platformers, where you have a gravity, so you have to check the Tile under you cause of that. In top down games this is not the case.
I am not using exactly this method, but the picture shows, what i am doing.
If you have any other questions feel free to ask.