I only have a basic 2D platformer right now with a tile-based map.
My AABB collision check code is this
int check_collision_rect(Rect A, Rect B)
{
//The sides of the rectangles
int leftA, leftB;
int rightA, rightB;
int topA, topB;
int bottomA, bottomB;
//Calculate the sides of rect A
leftA = A.x;
rightA = A.x + A.w;
topA = A.y;
bottomA = A.y + A.h;
//Calculate the sides of rect B
leftB = B.x;
rightB = B.x + B.w;
topB = B.y;
bottomB = B.y + B.h;
//If any of the sides from A are outside of B
if(bottomA <= topB)
{
return 0;
}
if(topA >= bottomB)
{
return 0;
}
if(rightA <= leftB)
{
return 0;
}
if(leftA >= rightB)
{
return 0;
}
//If none of the sides from A are outside B
return 1;
}
Then this is how I use it
Rect tile;
tile.h = 64;
tile.w = 64;
tile.x = 0;
tile.y = 0;
for(int i = 0; i < Map->tile_num; i++)
{
if(Map->tile[i]->type == 2) // Type 2 is a solid tile
{
if(check_collision_rect(player.pos, tile))
exit(0);
}
tile.x += 64;
if(tile.x >= LEVEL_WIDTH)
{
tile.x = 0;
tile.y += 64;
}
}
And here is my structure in case you guys feel it's important
typedef struct Rect {
int h, w;
float x, y;
float prev_x, prev_y; // Previous positions
float velX, velY; // Velocity for X and Y coordinate.
} Rect;
What is happening? Well, nothing. The game should exit when I collide with the solid tile, but it's not detecting the collision no matter how much I move. I put the for loop directly after my code where I move the player to a new position.
EDIT: I think I posted this prematurely after wondering for hours what the problem was. I think it may be that x and y are floats which might be causing the problems.