I want to create a contact listener in such a way that I'll be able to create a joint when sprites from different classes meet. I found a useful question and answer which has helped me - Getting the world's contactListener in Box2D partly. The following code and insrtuctions where recommended:
std::vector< std::pair<b2Fixture*, b2Fixture*> > thingsThatTouched;
//in BeginContact
thingsThatTouched.push_back( make_pair(contact->GetFixtureA(), contact->GetFixtureB()) );
//after the time step
for (int i = 0; i < thingsThatTouched.size(); i++) {
b2Fixture* fixtureA = thingsThatTouched[i].first;
b2Fixture* fixtureB = thingsThatTouched[i].second;
// ... do something clever ...
}
thingsThatTouched.clear(); //important!!
For this to work you'll need to make the thingsThatTouched list visible from the contact listener function, so it could either be a global variable, or you could set a pointer to it in the contact listener class, or maybe have a global function that returns a pointer to the list.
I am using Cocos2d and don't know much C++. How can I "make the thingsThatTouched list visible from the contact listener function" in Cocos2d? Should
std::vector< std::pair<b2Fixture*, b2Fixture*> > thingsThatTouched;
be in the ContactListener.h file? How will it differ in Cocos2d? Thanks.
Put this in a header file:
typedef std::pair<b2Fixture*, b2Fixture*> fixturePair;
typedef std::vector<fixturePair> fixturePairVector;
extern fixturePairVector g_touchingFixtures;
Then include the header wherever you need to use the list. You will also need to have this in a source file (.mm or .cpp) somewhere, just once:
fixturePairVector g_touchingFixtures;
Of cause, the typedefs are not necessary but they may help if you don't like looking at too many of the wrong kind of brackets.