How to get the force of a collision


I’m using a physics engine (cannon) and I would like to generate a sound if 2 objects collide.

There I ran into 2 problems:

  1. I would like get a notification if any collision happens. Either any collision of any object with any other object (PhysicsImposter). Or, any collision with one specific PhysicsImposter.
    I have found only OnCollideEvent but that is deprecated. The other collision events seem to require to register certain objects beforehand.

  2. I would like to know with which force/impulse the 2 objects collided. I would like to use this to control the volume of the played sound.

Welcome aboard!

Adding @Cedric

Hi @maziac

There is also onCollide for cannon PhysicsImpostor | Babylon.js Documentation

Unfortunately, I didn’t find any way to get the inter penetration depth. I can add that support for ammojs but I didn’t find anything for cannon. I guess something exists.
As a workaround, you can compute the distance between the position of impostor and the contact point. The shorter it is, the bigger the penetration.

@RaananW did you used penetration depth for your latest VR sound demo ?

The reason it is deprecated is performance. It does work however, and you can use it without the fear of it being removed any time soon.

Babylon.js doesn’t provide the native cannon.js event in the onCollideEvent callback, but you can register to it yourself. Something like this:

Lines 37-40 would be the ones interesting to you.

No, i didn’t. I register the collision for each generated sphere when it is created, against all existing colliders in the scene.

Demo will be released later today :slight_smile:

1 Like

The way I’m doing it, is by taking the difference in velocity of the last frame and the current frame. I then use this to calculate the impact, when a physics body is colliding with something. It’s not exactly the most accurate way, but it seems to work for me.

1 Like

Thanks a lot for all the good answers.
I have tried the addEventListener(“collide”, …) with getImpactVelocityAlongNormal().
This works very well for me.

1 Like

@Cedric do you know if that ^ approach would work in ammo.js too?

I think so, yes. I don’t see anything to would prevent it to work.