2011-12-31 34 views
0

MyContactListener類: .H嘗試使用聯繫人偵聽器。聽「contact.End()」不起作用。 (Box2D的,iPhone)

#import "Box2D.h" 
#import <vector> 
#import <algorithm> 

struct MyContact { 
    b2Fixture *fixtureA; 
    b2Fixture *fixtureB; 
    bool operator==(const MyContact& other) const 
    { 
     return (fixtureA == other.fixtureA) && (fixtureB == other.fixtureB); 
    } 
}; 

class MyContactListener : public b2ContactListener { 

public: 
    std::vector<MyContact>_contacts; 

    MyContactListener(); 
    ~MyContactListener(); 

    virtual void BeginContact(b2Contact* contact); 
    virtual void EndContact(b2Contact* contact); 
    virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold);  
    virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse); 

}; 

.mm

#import "MyContactListener.h" 

MyContactListener::MyContactListener() : _contacts() { 
} 

MyContactListener::~MyContactListener() { 
} 

void MyContactListener::BeginContact(b2Contact* contact) { 
    // We need to copy out the data because the b2Contact passed in 
    // is reused. 
    MyContact myContact = { contact->GetFixtureA(), contact->GetFixtureB() }; 
    _contacts.push_back(myContact); 
} 

void MyContactListener::EndContact(b2Contact* contact) { 
    MyContact myContact = { contact->GetFixtureA(), contact->GetFixtureB() }; 
    std::vector<MyContact>::iterator pos; 
    pos = std::find(_contacts.begin(), _contacts.end(), myContact); 
    if (pos != _contacts.end()) { 
     _contacts.erase(pos); 
    } 
} 

void MyContactListener::PreSolve(b2Contact* contact, const b2Manifold* oldManifold) { 
} 

void MyContactListener::PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) { 
} 

現在的問題:在我的更新方法我有這樣的代碼來檢查碰撞,如果接觸 * 結束 *:

std::vector<MyContact>::iterator pos3; 
    for(pos3 = contactListener->_contacts.end(); 
     pos3 != contactListener->_contacts.begin(); ++pos3) { 
     MyContact contact = *pos3; // here I get "EXE_BAD_ACCESS" 

     if (contact.fixtureA == detectorFixture || contact.fixtureB == detectorFixture) { 
     } 

    } 

但是我得到一個錯誤。 (標註在代碼註釋)

要檢查碰撞,如果接觸開始我有這樣的代碼,其工作原理:

std::vector<MyContact>::iterator pos; 
    for(pos = contactListener->_contacts.begin(); 
     pos != contactListener->_contacts.end(); ++pos) { 
     MyContact contact = *pos; 

     if (contact.fixtureA == detectorFixture || contact.fixtureB == detectorFixture) { 
     } 

    } 

公告了「」的聲明,我換了.begin()與.end()。這是不同的。

但它爲什麼不起作用?如果「接觸結束」,檢查燈具是否做錯了?

我之所以要這樣做的原因是,我想現在如果一個固定裝置觸摸任何東西/什麼都沒有。

回答

1
for(pos3 = contactListener->_contacts.end(); 
     pos3 != contactListener->_contacts.begin(); ++pos3) 

我想你應該將其替換爲:

for(pos3 = contactListener->_contacts.begin(); 
     pos3 != contactListener->_contacts.end(); ++pos3) 
+0

但是這不是我想要的。如果某件事與某件事有聯繫,它將被調用。但是我想讓我的身體分離。但我仍然找到了解決方案。 (請參閱box2d,我剛剛從那裏複製了聯繫人偵聽器。) – cocos2dbeginner 2012-01-04 21:41:18

相關問題