我正在使用Box2d处理(JS),我有两个机构,我希望其中一个在碰撞时消失,我试图使用“physics.removeBody(b1);”但不幸的是,我身上的所有尸体都消失了!这是碰撞功能中的代码。
void collision(Body b1, Body b2, float impulse) {
if (b2 == basket && b1.getMass() > 0) {
score += 10;
pop.cue(0);
pop.play();
physics.removeBody(b1);
}
}
答案 0 :(得分:0)
通常在创建实体时我会这样做:
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
}
关键是使用body的setUserData()函数来指定唯一标识符,然后使用body的getUserData()函数来检查并确保对象碰撞是您想要的。在您的示例中,您有Body b1和Body b2但不进行任何类型的测试以确保正确的物体发生碰撞。
我希望这会有所帮助