2d tilemap collision
Posted: Wed Sep 01, 2010 10:56 pm
Ok so I have been trying to create a way to have solid tiles in my game. Here is some of the code for the collision that I am using.
It looks long but it is just assignment of variables. But the problem with it is that I registers a collision everywhere except when the player is moved to the very top of the screen and with the cameraY at 0. The character is 40 pixels and I have no idea how to fix this. Please help. Thank you.
Code: Select all
bool IsCollision(SDL_Rect r1, SDL_Rect r2 )
{
if ( r1.x < r2.x+r2.w &&
r1.x+r1.w > r2.x &&
r1.y < r2.y+r2.h &&
r1.y+r1.h > r2.y )
{
return true;
}
return false;
}
int collision() {
SDL_Rect playerRect, tile[8];
playerRect = player.getPlayerRect();
bool solid[8];
tile[0].x = playerRect.x;
tile[0].y = playerRect.y/2;
tile[0].w = 32;
tile[0].h = 32;
tile[1].x = (playerRect.x) + 32;
tile[1].y = playerRect.y;
tile[1].w = 32;
tile[1].h = 32;
tile[2].x = (playerRect.x) + 32;
tile[2].y = (playerRect.y) - 32;
tile[2].w = 32;
tile[2].h = 32;
tile[3].x = playerRect.x;
tile[3].y = (playerRect.y)-32;
tile[3].w = 32;
tile[3].h = 32;
tile[4].x = (playerRect.x) - 32;
tile[4].y = (playerRect.y) + 32;
tile[4].w = 32;
tile[4].h = 32;
tile[5].x = (playerRect.x) - 32;
tile[5].y = (playerRect.y);
tile[5].w = 32;
tile[5].h = 32;
tile[6].x = (playerRect.x) - 32;
tile[6].y = (playerRect.y) + 32;
tile[6].w = 32;
tile[6].h = 32;
tile[7].x = (playerRect.x);
tile[7].y = (playerRect.y) + 32;
tile[7].w = 32;
tile[7].h = 32;
tile[8].x = (playerRect.x) + 32;
tile[8].y = (playerRect.y) + 32;
tile[8].w = 32;
tile[8].h = 32;
for (int i = 0; i < 8; i++) {
solid[i] = cMap[tile[i].y][tile[i].x];
}
for (int i = 0; i < 8; i++) {
if (solid[i] == true && IsCollision(playerRect, tile[i]) == true) {
printf("Collision!\n");
return 1;
}
}
return 0;
}