2D Tile based Game Collision problem
Posted
by
iNbdy
on Game Development
See other posts from Game Development
or by iNbdy
Published on 2012-04-09T10:17:45Z
Indexed on
2012/04/09
11:50 UTC
Read the original article
Hit count: 278
collision-detection
|tilemap
I've been trying to program a tile based game, and I'm stuck at the collision detection.
Here is my code (not the best ^^):
void checkTile(Character *c, int **map)
{
int x1,x2,y1,y2;
/* Character position in the map */
c->upY = (c->y) / TILE_SIZE; // Top left corner
c->downY = (c->y + c->h) / TILE_SIZE; // Bottom left corner
c->leftX = (c->x) / TILE_SIZE; // Top right corner
c->rightX = (c->x + c->w) / TILE_SIZE; // Bottom right corner
x1 = (c->x + 10) / TILE_SIZE; // 10px from left side point
x2 = (c->x + c->w - 10) / TILE_SIZE; // 10px from right side point
y1 = (c->y + 10) / TILE_SIZE; // 10px from top side point
y2 = (c->y + c->h - 10) / TILE_SIZE; // 10px from bottom side point
/* Top */
if (map[c->upY][x1] > 2 || map[c->upY][x2] > 2)
c->topCollision = 1;
else c->topCollision = 0;
/* Bottom */
if ((map[c->downY][x1] > 2 || map[c->downY][x2] > 2))
c->downCollision = 1;
else c->downCollision = 0;
/* Left */
if (map[y1][c->leftX] > 2 || map[y2][c->leftX] > 2)
c->leftCollision = 1;
else c->leftCollision = 0;
/* Right */
if (map[y1][c->rightX] > 2 || map[y2][c->rightX] > 2)
c->rightCollision = 1;
else c->rightCollision = 0;
}
That calculates 8 collision points
My moving function is like that:
void movePlayer(Character *c, int **map)
{
if ((c->dirX == LEFT && !c->leftCollision) || (c->dirX == RIGHT && !c->rightCollision))
c->x += c->vx;
if ((c->dirY == UP && !c->topCollision) || (c->dirY == DOWN && !c->downCollision))
c->y += c->vy;
checkPosition(c, map);
}
and the checkPosition:
void checkPosition(Character *c, int **map)
{
checkTile(c, map);
if (c->downCollision) {
if (c->state != JUMPING) {
c->vy = 0;
c->y = (c->downY * TILE_SIZE - c->h);
}
}
if (c->leftCollision) {
c->vx = 0;
c->x = (c->leftX) * TILE_SIZE + TILE_SIZE;
}
if (c->rightCollision) {
c->vx = 0;
c->x = c->rightX * TILE_SIZE - c->w;
}
}
This works, but sometimes, when the player is landing on ground, right and left collision points become equal to 1. So it's as if there were collision coming from left or right.
Does anyone know why this is doing this?
© Game Development or respective owner