Cocos2d Study Notes (9) Physical engine box2d 3

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.