我正在尝试开发碰撞检测。由于某种原因,冲突正在为LinkedList中的最后一个实体工作。我已尽力使用控制台调试它以查看它停止的位置,但我没有运气。所有其他实体都不工作,只有最后一个实体。这是代码:
public class Player implements Entity {
Image player;
public float x = 100f;
public float y = 100f;
boolean canGoLeft = true;
boolean canGoRight = true;
boolean canGoUp = true;
boolean canGoDown = true;
public float speed = 0.15f;
public Rectangle leftRect;
public Rectangle rightRect;
public Rectangle topRect;
public Rectangle bottomRect;
int i = 0;
Entities entities = new Entities();
public Player() {
}
public void update(GameContainer game, int delta) {
if(Keyboard.isKeyDown(Keyboard.KEY_D)) {
if(canGoRight) {
x += speed * delta;
}
}
if(Keyboard.isKeyDown(Keyboard.KEY_A)) {
if(canGoLeft) {
x -= speed * delta;
}
}
if(Keyboard.isKeyDown(Keyboard.KEY_W)) {
if(canGoUp) {
y -= speed * delta;
}
}
if(Keyboard.isKeyDown(Keyboard.KEY_S)) {
if(canGoDown) {
y += speed * delta;
}
}
for(Entity entity : Game.entities.entities) {
checkCollisions(entity);
}
}
public void render(GameContainer game, Graphics g) {
leftRect = new Rectangle(x, y + 5, 2, 80);
rightRect = new Rectangle(x + 45, y + 5, 2, 80);
topRect = new Rectangle(x + 6, y, 36, 2);
bottomRect = new Rectangle(x + 6, y + 90, 36, 2);
//rect = new Rectangle(200, 100, 60, 88);
try {
player = new Image("res/Player.png");
player.setFilter(Image.FILTER_NEAREST);
} catch (SlickException e) {
e.printStackTrace();
}
player.draw(x, y, 60, 88);
//g.draw(leftRect);
//g.draw(rightRect);
//g.draw(topRect);
//g.draw(bottomRect);
}
public void checkCollisions(Entity entity) {
// Collision Detection
canGoLeft = !leftRect.intersects(entity.getRect());
canGoRight = !rightRect.intersects(entity.getRect());
canGoDown = !bottomRect.intersects(entity.getRect());
canGoUp = !topRect.intersects(entity.getRect());
}
public Rectangle getRect() {
return null;
}
}
答案 0 :(得分:3)
遍历整个列表,但checkCollisions每次调用时都会覆盖canGoLeft,canGoRright等的值。
您应该执行类似
的操作canGoLeft = canGoLeft && !leftRect.intersects(entity.getRect());