Search code examples
libgdxcollision-detectioncollision

How to make the processing of collisions for objects of the same class?


// 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);
              }
    }
}

}

Somehow, all the objects Human (h1 and h2) make setX(h1.getX() + 2);. How to fix it? I need only one of them stepped aside


Solution

  • Maybe you can change the second loop so to avoid checking an object overlaps with itself (it will always do!) and also avoid checking each pair twice:

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