通常在创建身体时,我会这样做:
void makeBody(float x, float y) {
BodyDef bd = new BodyDef();
bd.type = BodyType.DYNAMIC;
bd.position.set(box2d.coordPixelsToWorld(x, y));
body = box2d.createBody(bd);
body.setUserData(this); // This is important
PolygonShape sd = new PolygonShape();
float box2dW = box2d.scalarPixelsToWorld(w/2);
float box2dH = box2d.scalarPixelsToWorld(h/2);
sd.setAsBox(box2dW, box2dH);
FixtureDef fd = new FixtureDef();
fd.setUserData("box");
// Attach Fixture to Body
body.createFixture(fd);
}
现在你的身体有一个 userData 属性,你可以像这样测试碰撞:
void beginContact (Contact cp) {
// Get both fixtures
Fixture f1 = cp.getFixtureA();
Fixture f2 = cp.getFixtureB();
// Get both bodies
Body b1 = f1.getBody();
Body b2 = f2.getBody();
// Get our objects that reference these bodies
Object o1 = b1.getUserData();
Object o2 = b2.getUserData();
//Detect player-enemy collision
if (b1.getUserData() == "player" && b2.getUserData() == "enemy") {
//... Do stuff here
}
if (b2.getUserData() == "player" && b1.getUserData() == "enemy") {
//... Do stuff here
}
重点是使用主体的 setUserData() 函数指定唯一标识符,然后使用主体的 getUserData() 函数检查并确保碰撞的对象是您想要的对象。在您的示例中,您有 Body b1 和 Body b2 但不进行任何类型的测试以确保正确的物体发生碰撞。
我希望这有帮助