box2d 碰撞监听

要监听碰撞,就应该用到box2d b2ContactListener类

其他废话不说了,直接上代码:

#ifndef ContactListener_H
#define ContactListener_H
#include "Box2D/Box2D.h"

class Contact
{
public:
	b2Fixture *fixtureA;
	b2Fixture *fixtureB;
};

class IContactListener
{
public:
	virtual void updateContact() = 0;
};

class ContactListener :
	public b2ContactListener
{
public:
	ContactListener(void);
	~ContactListener(void);

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

	void addListener(IContactListener* pContactListener);
public:
	std::list<Contact> contact_list;
};
#endif

#include "ContactListener.h"


ContactListener::ContactListener(void)
{

}


ContactListener::~ContactListener(void)
{
}

//! Callbacks for derived classes.
void ContactListener::BeginContact(b2Contact *contact)
{
	if (contact)
	{
		Contact c;
 		c.fixtureA = contact->GetFixtureA();
 		c.fixtureB = contact->GetFixtureB();

		contact_list.push_back(c);


	}
	else
	{
		CCLOG("error!");
	}
	B2_NOT_USED(contact);
}
void ContactListener::EndContact(b2Contact *contact)
{
	Contact myContact = { contact->GetFixtureA(), contact->GetFixtureB() };  
	std::list<Contact>::iterator posBegin =  contact_list.begin();
	std::list<Contact>::iterator posEnd =  contact_list.end();
	for (; posBegin != posEnd; posBegin++)
	{
		if(posBegin->fixtureA == contact->GetFixtureA() && posBegin->fixtureB == contact->GetFixtureB())
		{
			contact_list.erase(posBegin);
			break;
		}
	}

	B2_NOT_USED(contact);

}

void ContactListener::PreSolve(b2Contact *contact, const b2Manifold *oldManifold)
{
	B2_NOT_USED(contact);
	B2_NOT_USED(oldManifold);
}

void ContactListener::PostSolve(b2Contact *contact, const b2ContactImpulse *impulse)
{
	B2_NOT_USED(contact);
	B2_NOT_USED(impulse);
}


在word初始化的时候,调用

	m_plistener = new ContactListener();
	m_pworld->SetContactListener(m_plistener);

这样box2d监听就完成了

你可能感兴趣的:(box2d 碰撞监听)