LWJGL Java 2D collision when lagging
- by user1990950
I'm using a tile based collision, but when the game is lagging (the lag isn't the problem) the collision fails and the player falls through tiles.
This is the movement/collision detection code of my Player class:
gravity.y = gspeed;
speed.y+=gravity.y;
position.set(position.x + direction.x * speed.x * deltaSeconds, position.y + direction.y * speed.y * deltaSeconds);
for (int i = (int) Math.round(position.x / 32) - 2 * t; i < (int) Math.round(position.x / 32) + 3 * t; i++)
{
for (int j = (int) Math.round(position.y / 32); j < (int) Math.round((position.y + height + 64) / 32); j++)
{
checkCollision(i, j, deltaSeconds);
}
}
public void checkCollision(int i, int j, float deltaSeconds)
{
bbox.setBounds((int) position.x, (int) position.y, (int) width, (int) height);
Tile t = null;
t = Map.getTile(i, j);
if (t != null)
{
if (t.isSolid())
{
if (t.getTop().intersects(bbox))
{
if (position.y + height < t.y * 32 + 32)
{
if (speed.y >= 0)
{
position.y = t.y * 32 - height;
speed.y = 0;
gravity.y = 0;
jumpState = 0;
}
}
}
if (t.getBottom().intersects(bbox))
{
if (position.y < t.y * 32 + 32)
{
position.y = t.y * 32 + 32;
speed.y = 0;
}
}
else
{
if (t.getLeft().intersects(bbox))
{
if (position.x + width > t.x * 32)
{
position.x = t.x * 32 - width;
speed.x = 0;
}
}
if (t.getRight().intersects(bbox))
{
if (position.x < t.x * 32 + 32)
{
position.x = t.x * 32 + 32;
speed.x = 0;
}
}
}
}
}
}
Is it possible to fix my code, if yes how? Or is it possible to tell if the game is lagging?