I was reading the box2d manual and I saw that inter-frame contacts could only be picked up using b2ContactListener.
I created a class ActorListener (all active world objects are actors)
class ActorListener : public b2ContactListener
{
public :
ActorListener();
~ActorListener();
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);
};
And added it to my world when the game is initializing:
Listener = new ActorListener();
world->SetContactListener(Listener);
But as soon as an there is a collision I get an error in b2Contact.cpp
if (wasTouching == false && touching == true && listener)
{
listener->BeginContact(this); //EXC_BAD_ACCESS
}
Any ideas? Am I doing it wrong?
The setup code is correct. I would suggest some changes to the ActorListener class:
I’m not sure if these fixes change your problem. Changing my contact listener by adding constructor, destructor and changing to public virtual methods still did not cause a crash. So I assume it’s unlikely that the class interface is the problem.
Nevertheless, unless you need a constructor or destructor you can omit those. You should also remove the virtual keyword, as you provide the concrete implementation and don’t plan on subclassing ActorListener (right?). Non-virtual methods are a bit faster. Finally the methods should be private because only Box2D will call them, no other code should be allowed to call the methods in the ActorListener class. If you get compile errors after making these changes, then it may be related to the crash.
The crash indicates that in all likelihood the
listenerno longer points to valid memory, ie it has been deallocated. The other possibility might be that the actual code in BeginContact causes the crash but for some reason the debugger halts at the line making the call. You might want to set a breakpoint in BeginContact. And add the BeginContact implementation to your question.Finally, even though I assume the compiler will check this, is the file extension of the ActorListener implementation file set to .mm?