我知道这已被问过很多次,但我没有找到任何好的答案。
所以我的游戏中有一些实体,现在检查碰撞的最佳方法是什么?
链接:
代码说明:
我的世界级中有一个实体列表:
List<Entity> entities = new ArrayList<Entity>();
// 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。但为什么呢?
答案 0 :(得分:6)
这样做的经典方法是让Shape boundingBox与每个Entity相关联,然后在形状上使用Slick2d的“intersects”方法:
我相信有一种方法可以对精灵进行逐像素检查,但如果你不需要像素级精度,那么边界框方法会更有效。
一些代码:
在您的实体抽象类中添加:
private Shape boundingBox;
public Shape getBoundingBox() {
return this.boundingBox;
}
然后你的交叉方法是:
public boolean intersects(Entity entity) {
if (this.getBoundingBox() == null) {
return false;
}
return this.getBoundingBox().intersects(entity.getBoundingBox());
}
然后,您需要为要检查冲突的每个实体设置一个边界框。