Physics collision callbacks using ammo

From the documentation it seems like we need to get physics collision callbacks as per this demo: Babylon.js Playground
Is there a better and more general way to get callbacks?
Ideally I would like to register a callback that fires regardless of what bodies collide (I don’t want to provide a list of ALL bodies in the world every time I register one). I would also need to get more information from the collision, for example the incoming and outgoing velocities of both bodies so I can determine the energy loss.

1 Like

Hi Shahin, I think this PG can help:

sphere.physicsImpostor.onCollideEvent = (self, other) => {
    console.log(`onCollideEvent: self velocity: ${self.getLinearVelocity()}, other velocity: ${other.getLinearVelocity()}`);

self and other can give useful information for both bodies

Thanks. I did see that function but it said it was for legacy code:

Note that I’m using ammo, not cannon, and it seems like I actually need to call registerOnPhysicsCollide() otherwise onCollideEvent() never gets called because the physicsImpostor._onPhysicsCollideCallbacks needs to have a length > 0 otherwise we get no callbacks at all (for ammo only).
So now that I have a workaround, the problem remaining is that I need both the pre solve and post solve collision velocities of the bodies so I can determine the energy lost. It seems like the velocities I get in at the point of callback are presolve… any good way to get the velocities after collision?

Adding @Cedric who will be able to provide guidance after the break :slight_smile:

I’m not sure how well this would work, but maybe we could use onBeforeStepObservable and onAfterStepObservable in conjunction with registerOnPhysicsCollide to get before and after velocities


Yup this is a great idea :slight_smile: @Shahin you might be able to rely on both observables onBeforeStepObservable and onAfterStepObservable availabled on the scene to do this.

1 Like

My mistake, I think onBeforeStepObservable and onAfterStepObservable is only available when using Deterministic Lockstep (Advanced Animation Methods | Babylon.js Documentation)

I think onBeforePhysicsObservable and onAfterPhysicsObservable should work if not using Deterministic Lockstep

1 Like

I ended up using

  • physicsImpostor.registerOnPhysicsCollide: to get pre collision velocity and mark the body
  • physicsImpostor.registerBeforePhysicsStep: to get post collision velocity of marked body
  • physicsImpostor.registerAfterPhysicsStep: not really needed

I couldn’t get physicsImpostor.onCollideEvent() to work in ammo.js because this code (Babylon.js/ammoJSPlugin.ts at 38bc17b050db8f854fc27069ecea552114cb21f2 · BabylonJS/Babylon.js · GitHub) filters out any bodies that haven’t been passed to registerOnPhysicsCollide. It isn’t ideal, but it works.