cocos2d學習筆記(九)物理引擎box2d之三

來源:互聯網
上載者:User

今天寫個跟sensor相關的部落格

sensor的建立跟其他剛體的建立一樣,只是將b2FixtureDef的isSensor設為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);}

運行後,綠色地區就是我們的sensor

我們可以看到sensor是可以讓剛體穿過的。

我們在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;    }

這時候,我們在sensor上方點擊建立出來的物體,掉到sensor上立馬就消失了。注意,這裡的檢測會有一個bug,假如某個物體移動很快,update方法前在sensor這邊,第二次update有可能穿出sensor而未被檢測到。一般sensor可以用在我們的人物來到特定的位置觸發一些事件等等,以後我們再細說更好的碰撞檢測方法,今天先寫這麼多。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.