如何通过地面夹具防止isSensor = true的灯具?

时间:2013-11-15 00:04:17

标签: cocos2d-iphone box2d

我在可视区域周围创建边框。在这个区域内,我正在创建其他夹具,这些夹具是用于碰撞检测的传感器。似乎具有isSensor = true的灯具穿过窗口边框。我怎样才能防止这种情况发生?谢谢!

    bodyDef.type = b2_dynamicBody;
    bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);
    b2Body *body = world->CreateBody(&bodyDef);

    // Define another box shape for our dynamic body.
    b2PolygonShape dynamicBox;
    dynamicBox.SetAsBox(.5f, .5f);//These are mid points for our 1m box

    // Define the dynamic body fixture.
    b2FixtureDef fixtureDef;
    fixtureDef.shape = &dynamicBox; 
    fixtureDef.density = 1.0f;
    fixtureDef.friction = 0.3f;
    fixtureDef.isSensor = true; //causes fixtures to fall through border
    body->CreateFixture(&fixtureDef);

窗口边框:

 CGSize screenSize = [CCDirector sharedDirector].winSize;
 float widthInMeters = screenSize.width / PTM_RATIO;
 float heightInMeters = screenSize.height / PTM_RATIO;
 b2Vec2 lowerLeftCorner = b2Vec2(0, 0);
 b2Vec2 lowerRightCorner = b2Vec2(widthInMeters, 0);
 b2Vec2 upperLeftCorner = b2Vec2(0, heightInMeters);
 b2Vec2 upperRightCorner = b2Vec2(widthInMeters, heightInMeters);

b2BodyDef screenBorderDef;
screenBorderDef.position.Set(0, 0);
b2Body* screenBorderBody = world->CreateBody(&screenBorderDef);
b2EdgeShape screenBorderShape;

screenBorderShape.Set(lowerLeftCorner, lowerRightCorner);
screenBorderBody->CreateFixture(&screenBorderShape, 0);
screenBorderShape.Set(lowerRightCorner, upperRightCorner);
screenBorderBody->CreateFixture(&screenBorderShape, 0);
screenBorderShape.Set(upperRightCorner, upperLeftCorner);
screenBorderBody->CreateFixture(&screenBorderShape, 0);
screenBorderShape.Set(upperLeftCorner, lowerLeftCorner);
screenBorderBody->CreateFixture(&screenBorderShape, 0);

2 个答案:

答案 0 :(得分:1)

在PostCollision方法

中将isSensore设为false并检查碰撞

答案 1 :(得分:0)

一种方法是将第二个夹具添加到其上有传感器的主体上,并设置碰撞过滤器,使其仅与边界碰撞。您需要了解一下如何使用碰撞过滤器设置,一开始可能有点棘手。这可能会有所帮助:http://www.iforce2d.net/b2dtut/collision-filtering

默认情况下,类别位值为1,因此除非您更改了任何内容,否则场景中的所有灯具都有类别1.要区分边框和其他灯具,您必须为它们指定不同的类别。假设你做了地面夹具类别2:

screenBorderFixtureDef.filter.categoryBits = 2;

mask的默认值是0xFFFF,因此所有现有灯具仍将像以前一样与边框碰撞,即使类别更改如此。然后,为了使新添加的第二个夹具忽略除边框之外的所有夹具,您可以将蒙版设置为仅与边框碰撞:

fixtureDef.filter.maskBits = 2;

<小时/> 另一种方法是使现有的传感器夹具不是传感器,使其与边界碰撞。但当然,它也会与其他一切相冲突。您可以使用联系人侦听器的PreSolve回调来表示某些联系人不应该执行任何冲突响应:

//in PreSolve
if ( this is NOT a contact between border and sensor )
    contact->SetEnabled( false );