如何对相同class的物体进行碰撞处理?
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);
}
}
}
}
不知何故,所有对象 Human(h1 和 h2)使 setX(h1.getX() + 2);
。如何解决?我只需要他们中的一个让位
也许你可以改变第二个循环,以避免检查对象与自身重叠(它总是会这样做!)并且避免检查每对两次:
for (int j=i+1; j<activeHumans.size(); j++) ...
// 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);
。如何解决?我只需要他们中的一个让位
也许你可以改变第二个循环,以避免检查对象与自身重叠(它总是会这样做!)并且避免检查每对两次:
for (int j=i+1; j<activeHumans.size(); j++) ...