0
votes

i want to rotate a sprite and move forward after a collisions occurs with a object. The collision has to be using Box2d since i need pixel perfect collision. i have the header and implementation class for contactlistener but how do i implement it in the main class ?

my .h file for contact listener is

 #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);

};

This is my .M file for contact listener

    #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) {    
}     

In the main class i have

contactListner = new MyContactListener;
world->SetContactListener(contactListner);

After this how do i check for collision in the scheduler method ?

Thanks for the help

1

1 Answers

0
votes

in your scheduler method, loop through contacts, check if collision is ok:

for(pos = _contactListener->_contacts.begin(); 
        pos != _contactListener->_contacts.end(); ++pos) {
            MyContact contact = *pos;
     if(contact->fixtureA == ball && contact->fixtureB == wall){
        //Do something
     }
}