联系Box2d Cocos2d中的监听器

时间:2011-09-04 18:53:45

标签: iphone cocos2d-iphone box2d

我想旋转精灵并在与对象发生碰撞后向前移动。 碰撞必须使用Box2d,因为我需要像素完美碰撞。 我有contactlistener的头和实现类,但我如何在主类中实现它?

联系人监听器的.h文件是

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

};

这是我的联系人监听器的.M文件

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

在主要班级我有

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

在此之后如何在调度程序方法中检查冲突?

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

在您的调度程序方法中,循环浏览联系人,检查碰撞是否正常:

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