Today, I wrote a blog related to sensor.
The creation of sensor is the same as that of other rigid bodies, but the issensor of b2fixturedef is set to true.
- (void)createSensor{ CGSize winSize = [[CCDirector sharedDirector] winSize]; CGSize sensorSize = CGSizeMake(100, 50); b2BodyDef bodyDef; bodyDef.type = b2_staticBody; bodyDef.position = b2Vec2((winSize.width-sensorSize.width/2)/PTM_RATIO, (sensorSize.height/2)/PTM_RATIO); sensorBody = world->CreateBody(&bodyDef); b2PolygonShape shape; shape.SetAsBox(sensorSize.width / PTM_RATIO, sensorSize.height / PTM_RATIO); b2FixtureDef fixtureDef; fixtureDef.shape = &shape; fixtureDef.isSensor = true; sensorBody->CreateFixture(&fixtureDef);}
After running, the green area is our sensor.
We can see that the sensor allows the rigid body to pass through.
Add the following code to update:
b2ContactEdge* edge = sensorBody->GetContactList(); while (edge) { b2Contact* contact = edge->contact; b2Fixture* fixtureB = contact->GetFixtureB(); b2Body *bodyB = fixtureB->GetBody(); if (bodyB != sensorBody && bodyB != groundBody) { CCSprite *sprite = (CCSprite *)bodyB->GetUserData(); [sprite removeFromParentAndCleanup:YES]; world->DestroyBody(bodyB); bodyB = NULL; break; } edge = edge->next; }
At this time, we click the created object on the top of the sensor and it will disappear immediately after it falls onto the sensor. Note: The detection here has a bug. If an object moves fast, it will be on the sensor side before the update method. The second update may be passed through the sensor but not detected. Generally, sensor can be used to trigger some events when our characters come to a specific position. We will elaborate on a better collision detection method later. So much will be written today.