Reputation: 503
I've been using ray wenderlich's contact listener and it's been working well for detecting contacts but I don't understand how to modify it to also tell me when a contact ends.
I want to add a sensor to my enemies so they can detect when a floor ends and turn around instead of falling .
can anyone explain how to modify this listener or point me to a different listener than detect contact ends?
//MyContactListener.mm
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) {
}
For detecting contacts I use the following..
for(pos = _contactListener->_contacts.begin();
pos != _contactListener->_contacts.end(); ++pos) {
MyContact contact = *pos;
b2Body *bodyA = contact.fixtureA->GetBody();
b2Body *bodyB = contact.fixtureB->GetBody();
CCSprite *spriteA = (CCSprite *) bodyA->GetUserData();
CCSprite *spriteB = (CCSprite *) bodyB->GetUserData();
//...do stuff
}
Upvotes: 0
Views: 322
Reputation: 24846
You are storing contacts that have begun in _contacts
. Instead you can have two vectors std::vector<MyContact>
. First for begun contacts (_begin
) and second for ended contacts (_end
). When your listener receives message that contact has ended - remove it from _begin
and
insert into _end
. In that case you will be able to iterate over both types of contacts. Just don't forget to clear
_end
contacts when you are done with them.
Also for detecting if floor ended is better to use ray cast. You can google for using ray cast in box2d
Upvotes: 2
Reputation: 554
When the size of _contactListner->_contact.size() is zero at that time there is no contact. So when there is contact in world there will be some value in the _contact vector and when it become zero , that suggests that there is no contact further more:that is the end of the contact.
Upvotes: 0