Hello everyone!
I often see tutorials about tile collisions, which provide a simple function that detects if an object overlaps a tile valued "solid" (1 in example), by checking one of its 2 points (x,x+w or y,y+h) a time over a simple tile map, and return a collision coordinates, or returning a dynamic list of coordinates in some cases.
I was wondering, if I avoid generating a dynamic array of coordinates but apply a callback directly to the collision detection, would it be considered a bad practice?
I want to stick to plain values map instead of an array of complex tile structure, and avoid any dynamic list of collided tiles if possible.
This is a pseudo example on how I imagined the thing:
void collisionResponse(Object *pobj, int x, int y, int tile)
{
if(tile==1)
{
//Solid tile type
pobj->x = x-pobj->w;
return 1;
}
else if(tile==2)
{
//Ladder tile type
if(button(UP))
{
player.state = climb;
}
return 0;
}
else if(tile==3)
{
//Water tile type
player.state = swim;
return 0;
}
return 1;
}
void tileCollision(Object *object, int x, int y, void (*callback)(Object*, int, int, int) )
{
int left_tile = object->x / 16;
int right_tile = (object.x+object->w) / 16;
int top_tile = object->y / 16;
int bottom_tile = (object->y + object->w) / 16;
for(int i=left_tile; i<=right_tile; i++)
{
for(int j=top_tile; j<=bottom_tile; j++)
{
int tile = getTile(i, j)
if(tile != 0)
{
if(__callback(object, i, j, tile))
break;
}
}
}
}
tileCollision(player, player->x+player->speed, player->y, &collisionResponse);
I like the idea to be able to apply different callbacks to different objects with different behaviours, but, what's your opinion about?