我正在努力让游戏中的碰撞变得完美。我正在测试的是,如果你的玩家撞到了墙上,你就会停下来。我只实现了当玩家撞击墙壁左侧时(当墙壁位于玩家右侧时)的碰撞代码。这是代码。
if(entityOnRight){
if(player.getPositionCorner(SquareMapTuples.BOTTOM_RIGHT).x -
ent.getPositionCorner(SquareMapTuples.BOTTOM_LEFT).x > -.9f)
player.setMovementBooleans(false, false, false, false);
else
player.setMovementBooleans(true, false, false, false);
}
注意:如果我走得很慢,它会将玩家停在我希望它停止的地方,但走得很快,它不会按照我想要的方式进行碰撞
本质上,代码声明如果墙在右侧,它将检查玩家矩形的右下角,减去墙的左下角,并检查两者之间的距离是否为 0.001 。 0.001 几乎是一个不易察觉的距离,因此我使用这个值。这是 player.setMovementBooleans
的代码
public void setMovementBooleans(boolean canMoveRight, boolean canMoveLeft, boolean canMoveUp, boolean canMoveDown){
this.canMoveRight = canMoveRight;
if(canMoveRight == false && moveRight)
vel.x = 0;
}
Player
类中的 canMoveRight
boolean 值(不在参数中)允许您移动,moveRight
是当您正在努力向右移动。下面是一些代码,可以更好地解释这些 boolean 值如何交互:
//If you clicked right arrow key and you're not going
//Faster then the max speed
if(moveRight && !(vel.x >= 3)){
vel.x += movementSpeed;
}else if(vel.x >= 0 && !moveRight){
vel.x -= movementSpeed * 1.5f;
System.out.println("stopping");
//Make sure it goes to rest
if(vel.x - movementSpeed * 1.5f < 0)
vel.x = 0;
}
和:
if(Gdx.input.isKeyPressed(Keys.D) && canMoveRight)
moveRight = true;
else
moveRight = false;
总结一下,如果你点击“D”键,它就可以让你开始移动。但是,如果 boolean 值 canMoveRight
为 false,则它不会移动您。这是显示发生情况的图像(玩家是黄色,墙壁是绿色)
正如您所看到的,播放器比我想要的要走得更远。它应该在此时停止:
非常感谢任何有关如何实现这一目标的帮助!
最佳答案
也许您尝试的方式有点太复杂了:-)。我建议从头开始采用一种更简单的方法:将 map 和播放器设为 com.badlogic.gdx.math.Rectangle 实例。现在,在以下代码部分中,您将检查移动后玩家是否仍在 map 内,如果是,则允许移动,如果不是,则不允许:
if(Gdx.input.isKeyPressed(Keys.D){
float requestedX, requestedY;
//calculate the requested coordinates
Rectangle newPlayerPositionRectangle = new Rectangle(requestedX, requestedY, player.getWidth(), player.getHeight());
if (newPlayerPositionRectangle.overlaps(map) {
//move the player
} else {
//move the player only to the edge of the map and stop there
}
}
关于java - LibGdx Java 中近乎完美的碰撞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37428315/