Hello,
I’m currently trying to build a platformer game and try to get the collision detection working. The code for the collision detection is the following. It is basicly the code from the LibGDX test game superkalio:
private void checkCollisionsPlayervsMap(float deltaTime) {
// perform collision detection & response, on each axis, separately
// if the player is moving right, check the tiles to the right of it's
// right bounding box edge, otherwise check the ones to the left
Rectangle playerRect = rectPool.obtain();
playerRect.set(player.position.x, player.position.y, Player.width, Player.height);
int startX, startY, endX, endY;
if (player.velocity.x > 0) {
startX = endX = (int) (player.position.x + Player.width + player.velocity.x);
} else {
startX = endX = (int) (player.position.x + player.velocity.x);
}
startY = (int) (player.position.y);
endY = (int) (player.position.y + Player.height);
getTiles(startX, startY, endX, endY, tiles);
playerRect.x += player.velocity.x;
for (Rectangle tile : tiles) {
if (playerRect.overlaps(tile)) {
player.velocity.x = 0;
break;
}
}
playerRect.x = player.position.x;
// if the player is moving upwards, check the tiles to the top of it's
// top bounding box edge, otherwise check the ones to the bottom
if (player.velocity.y > 0) {
startY = endY = (int) (player.position.y + Player.height + player.velocity.y);
} else {
startY = endY = (int) (player.position.y + player.velocity.y);
}
startX = (int) (player.position.x);
endX = (int) (player.position.x + Player.width + player.velocity.x);
getTiles(startX, startY, endX, endY, tiles);
playerRect.y += player.velocity.y;
for (Rectangle tile : tiles) {
if (playerRect.overlaps(tile)) {
if (player.velocity.y > 0) {
player.position.y = (tile.y - Player.height);
} else {
player.position.y = (tile.y + tile.height);
player.grounded = true;
}
player.velocity.y = 0;
break;
}
}
rectPool.free(playerRect);
// unscale the velocity by the inverse delta time and set
// the latest position
player.position.add(player.velocity);
player.velocity.scl(1 / deltaTime);
// Apply damping to the velocity on the x-axis so the player dosen't
// walk infinitely once a key was pressed
player.velocity.x *= Player.DAMPING;
}
private void getTiles(int startX, int startY, int endX, int endY, Array<Rectangle> tiles) {
TiledMapTileLayer layer = (TiledMapTileLayer) map.getLayers().get("ground");
rectPool.freeAll(tiles);
tiles.clear();
for (int y = startY; y <= endY; y++) {
for (int x = startX; x <= endX; x++) {
Cell cell = layer.getCell(x, y);
if (cell != null) {
Rectangle rect = rectPool.obtain();
rect.set(x, y, 1f, 1f);
tiles.add(rect);
}
}
}
}
The problem is, sometimes when I’m jumping towards an edge, the player gets stuck on it. See the following gif:
Can someone help me to get the code working right? Or do you need more information?