如何处理同类对象的冲突?

时间:2016-11-21 13:28:34

标签: libgdx collision-detection collision

// array containing the active humans.
public final Array<Human> activeHumans = new Array<Human>();
// object pool.
public final Pool<Human> humanPool = new Pool<Human>() {
    @Override
    protected Human newObject() {
        return new Human(100, 500);
    }
};

............................................... .............................

@Override
public void update(float dt) {
checkCollisions();
}

public void checkCollisions() {

// human-human collision
    for (int i=0; i<activeHumans.size(); i++) {
    Human h1 = activeHumans.get(i);

    for (int j=0; j<activeHumans.size(); j++) {
        Human h2 = activeHumans.get(j);

        if (h1.getRectangle().overlaps(h2.getRectangle())) {
                h1.setX(h1.getX() + 2);
              }
    }
}

}

不知何故,所有对象Human(h1和h2)都会setX(h1.getX() + 2);。怎么解决?我只需要将其中一个放在一边

1 个答案:

答案 0 :(得分:1)

也许你可以改变第二个循环,以避免检查一个与自身重叠的对象(它总是这样做!)并且还避免检查每一对两次:

for (int j=i+1; j<activeHumans.size(); j++) ...