I am working on a 2D tile based platformer and was hoping to get someone to review my collision detection. I've only included the X collision check since the Y is essentially the same. Any suggestions/criticisms are appreciated.
// Corrects X movement if a collision occurs.
private void checkXCollision()
{
// Find the range of tiles the player intersects
Point topLeft = new Point(((int)(xtemp + dx) - collisionWidth/2) / map.getTileSize(), ((int)ytemp - collisionHeight/2) / map.getTileSize());
Point bottomRight = new Point(((int)(xtemp + dx) + collisionWidth/2) / map.getTileSize(), ((int)ytemp + collisionHeight/2) / map.getTileSize());
// Left
if(dx < 0)
{
boolean collision = false;
for(int row = topLeft.y; row <= bottomRight.y; row++)
{
if(map.getType(row, topLeft.x) == Tile.SOLID)
{
collision = true;
break;
}
}
if(collision)
{
dx = 0;
// Move player to edge of solid tile
int col = ((int)(xtemp + dx) - collisionWidth/2) / map.getTileSize();
xtemp = col * map.getTileSize() + collisionWidth / 2;
}
else
{
xtemp += dx;
}
}
// Right
if(dx > 0)
{
boolean collision = false;
for(int row = topLeft.y; row <= bottomRight.y; row++)
{
if(map.getType(row, bottomRight.x) == Tile.SOLID)
{
collision = true;
break;
}
}
if(collision)
{
dx = 0;
// Move player to edge of solid tile
int col = ((int)(xtemp + dx) + collisionWidth/2) / map.getTileSize();
xtemp = (col + 1) * map.getTileSize() - collisionWidth / 2 - 1;
}
else
{
xtemp += dx;
}
}
}