我遇到了同样的问题,感谢@Rooban 和他的评论“fixture.isSensor=true;” 我解决了。我正在使用 box2dweb(JavaScript 端口),因为所有 box2d API 都相似,所以这可能会对您有所帮助。
假设你有两个对象,一个墙和一个玩具。玩具正在穿过墙壁。
//WALL (toy detector)
var toyDetectorFixDef = new box2d.b2FixtureDef();
toyDetectorFixDef.density = 1;
toyDetectorFixDef.friction = 0.5;
toyDetectorFixDef.restitution = 0.5;
toyDetectorFixDef.shape = new box2d.b2PolygonShape;
toyDetectorFixDef.shape.SetAsBox(80 / SCALE, 5 / SCALE);//, new box2d.b2Vec2(bodyDef3.x, bodyDef3.y ), 4);
//BE SURE YOU ADDED THIS LINE, SO THIS OBJECT IS ACTING AS A SENSOR
toyDetectorFixDef.isSensor = true;
var toyDetectorBodyDef = new box2d.b2BodyDef();
toyDetectorBodyDef.type = box2d.b2Body.b2_staticBody;
toyDetectorBodyDef.position.x = 100 / SCALE;
toyDetectorBodyDef.position.y = 280 / SCALE;
var rbDataToyDetector = new Object();
rbDataToyDetector.bodyType = "toyDetector";
toyDetectorBodyDef.userData = rbDataToyDetector;
var toyDetectorBox = world.CreateBody(toyDetectorBodyDef);
toyDetectorBox.CreateFixture(toyDetectorFixDef);
然后你必须添加 TOY 对象。
//TOY object
var fixDef = new box2d.b2FixtureDef();
fixDef.density = 1;
fixDef.friction = 0.5;
fixDef.restitution = 0.5;
bodyDef = new box2d.b2BodyDef();
bodyDef.type = box2d.b2Body.b2_dynamicBody;
bodyDef.position.x = 200 / SCALE + Math.random() * 400 / SCALE;
bodyDef.position.y = 0;
var rbDataBall = new Object();
rbDataBall.bodyType = "toy";
bodyDef.userData = rbDataBall;
fixDef.shape = new box2d.b2CircleShape(20 / SCALE);
var toyBox = world.CreateBody(bodyDef);
toyBox.CreateFixture(fixDef);
现在,当您拥有对象时,您必须检查碰撞。
try {
var listener = new Box2D.Dynamics.b2ContactListener;
listener.BeginContact = function (contact) {
if ((contact.GetFixtureA().GetBody().GetUserData().bodyType == "toyDetector" && contact.GetFixtureB().GetBody().GetUserData().bodyType == "toy") ||
(contact.GetFixtureA().GetBody().GetUserData().bodyType == "toy" && contact.GetFixtureB().GetBody().GetUserData().bodyType == "toyDetector")) {
//YOUR CODE HERE
console.log("Toy detected!");
}
}
world.SetContactListener(listener);
}
catch (e) {
console.log(e.toString());
}
我希望这能帮到您。