I have used this code, or code very similar to it, to detect collisions between rectangle shaped entities and a tilemap for a long time. When I read the code it seems to me that it is impossible for an entity to wind up intersecting with a non-traversable (solid, as I call it in the code) tile but sometimes when I'm testing a game a character gets stuck half-inside of a wall or tree or something.
Here's the code, can anyone figure out how the entity could possibly wind up in a solid tile?
public void moveX(float mx, Level level) {
//tile(float pos) returns the tile for the position, in this case since tiles are 16x16 it returns Math.floor(pos / 16)
float newx = x + mx;
if(tile(x + width) != tile(newx + width)) { //if the right side of the new position isnt on the same tile as the previous position
for(int Y = tile(y); Y <= tile(y + height); Y++) { //check this once for every vertical tile the entity touches
if(level.isSolid(tile(newx + width), Y)) { //check if the new tile is solid of traversable
isTerrainCollision(level, tile(newx + width), Y); // if it is, call terraincollision function and
newx = x; // move back to previous position
}
}
}else if(tile(x) != tile(newx)) { // do the same for the left side of the entity
for(int Y = tile(y); Y <= tile(y + height); Y++) {
if(level.isSolid(tile(newx), Y)) {
isTerrainCollision(level, tile(newx), Y);
newx = x;
}
}
}
x = newx;
}
