我在自上而下的2D滚动游戏中实现了基本的碰撞检测。如果玩家移动的距离较大,它将跳过其周围的区域,因为碰撞检测会在移动后在玩家周围进行检查。除此之外,玩家可能会卡在瓷砖中。
我尝试将运动递归地切成两半,以检查是否可以找到少量不会在碰撞中结束的运动,但是我似乎无法使这对任何一个问题都起作用。它还会导致StackOverflow错误。
在下面的代码中,x()表示玩家从左下角开始的X位置。 y()是Y位置。 size是播放器的宽度和高度,而prevX和curX是临时变量。 tile方法可从播放器获取特定半径范围内的所有tile位置。
move(motionx, motiony);
if (x() - size()/2 < 0)x(size()/2);
if (y() - size()/2 < 0)y(size()/2);
if (x() + size()/2 > game.mapWidth * game.chunkWidth * size)x(game.mapWidth*game.chunkWidth*size - size()/2);
if (y() + size()/2 > game.mapHeight * game.chunkHeight * size)y(game.mapHeight*game.chunkHeight*size - size()/2);
float curX = x();
boolean updateX = true;
boolean updateY = true;
for (float[] tile : game.tiles((float)Math.ceil((double)size()/(double)size))) {
Tile t = game.tile(tile[0], tile[1]);
if (t == null) continue;
if (t.solid && game.collision(game.coordinate(), tile)) {
factor(1.0f - t.bounce, 1.0f - t.bounce);
x(game.prevX);
updateX = false;
if (t.solid && game.collision(game.coordinate(), tile)) {
x(curX);
updateX = true;
y(game.prevY);
updateY = false;
if (t.solid && game.collision(game.coordinate(), tile)) {
x(game.prevX);
updateX = false;
}
}
}
}
if (updateX)game.prevX = x();
if (updateY)game.prevY = y();
我希望这可以完美地阻止玩家移动到实体砖上,但是显然存在问题。我不擅长碰撞,但愿意尝试任何事情。有时会跳过图块和/或卡住。