Slick2d | 实体碰撞检测
问题:
我知道这已被问过多次,但我没有找到任何好的答案。
所以我的游戏中有一些实体,现在检查碰撞的最佳方法是什么?
链接:
游戏(完成)
代码说明:
我的世界级中有一个实体列表:
List entities = new ArrayList(); // The list in the World class
我用这段代码更新它们(仅在视图范围内):
public void update(GameContainer gc, int delta) { for (int i = 0; i < entities.size(); i++) { entities.get(i).update(gc, delta); } } // Update entities
所以现在我想检查实体更新方法中的碰撞。
我试过这个作为我的更新方法:
@Override public void update(GameContainer gc, int delta) { for (Entity entity : world.entities) { if (intersects(entity)) { // world.remove(this); } } } // The update method of an entitiy
这是当前的instersects方法:
public boolean intersects(Entity entity) { if (entity instanceof Player) { // Do nothing } else { if (shape != null) { return this.getShape().intersects(entity.getShape()); } } return false; } // The intersects method of the abstract Entity class
目前,intersects方法始终返回true。 但为什么?
这样做的经典方法是让Shape boundingBox与每个Entity关联,然后在形状上使用Slick2d的“intersects”方法:
我相信有一种方法可以对精灵进行逐像素检查,但如果您不需要像素级精度,则边界框方法会更有效。
一些代码:
在您的Entity抽象类中添加:
private Shape boundingBox; public Shape getBoundingBox() { return this.boundingBox; }
然后你的intersects方法是:
public boolean intersects(Entity entity) { if (this.getBoundingBox() == null) { return false; } return this.getBoundingBox().intersects(entity.getBoundingBox()); }
然后,您需要为要检查冲突的每个实体设置边界框。