Page 1 of 1

Calculating collision response using collision callbacks

Posted: Tue Sep 09, 2014 2:11 pm
by ptc79
Hi, I would like to know the correct technique for calculating the collision response applied to bodies, with reference to the collision callbacks.

For example, suppose there is a dynamic body with a circular fixture, trapped inside a rectangular loop shape fixture of a static body. If I set the fixtures of both bodies to have a restitution of zero, the circular shape will not bounce when an impulse is applied to it, and it hits the edge of the other fixture. How do I use the callbacks to make the circular body bounce around like its fixture has a restitution of 1, and it is perfectly elastic. Thanks for your help.

Re: Calculating collision response using collision callbacks

Posted: Wed Sep 10, 2014 9:13 pm
by iforce2d
I think the only way you can guarantee a perfectly elastic collision is to 'repair' the velocity after the collision has finished. Unfortunately this is really only possible in the most simple collision (between only two things at a time).

Basically, in the EndContact callback of your contact listener, you note when the two fixtures have finished touching, and after the time step has finished (remember you can't change anything inside the callbacks) you can do SetLinearVelocity so that the momentum is perfectly conserved.

This is a really hacky solution but I really don't know of a nicer way. The reason I said it only works for a simple collision between two objects is, taking your example, what should happen when the circle touches two sides of the container at the same time, then does EndContact with each of them in two separate time steps? I guess you could try making sure that the velocity update is only done when all contacts have finished... might be ok.

Hmmm... having said that, if you are hoping to do this with the restitution of both fixtures set to zero, I don't think that will work. What I'm talking about here would rely on using Box2D to calculate the correct bounce direction for you, so you would need to set a high restitution for that.

If you want to give things a different restitution depending on what they collide with, you might be interested in the SetRestitution function of b2Contact.
https://code.google.com/p/box2d/source/ ... tact.h#128
You can call that in BeginContact to override the restitution value for specific pairs of fixtures.