Using AmmoJS with Babylon

I’ve been trying to figure out how to properly use Cannon or Ammo for physics in BabylonJS but the documentation on this is very sparse.

Starting with AmmoJS I’m using the npm package “ammo.js”, there also seems to be one called “ammojs” so I’m not sure which is correct but I believe the former is what I’ve seen used. I’m using Typescript and this is what I have written:

import * as Ammo from "ammo.js";
  async CreatePhysics(): Promise<void> {
    await  Ammo();
    this.scene.enablePhysics(
      new Vector3(0, -9.81, 0),
      new AmmoJSPlugin(true, Ammo)
    );
   }

I get an error about type definitions for ammo.js and it looks like none exist when I try to run
npm i --save-dev @types/ammo.js

I did find these topics in the forum:

Unfortunately, even after following what was mentioned there I still don’t get around this issue. I assume the definitions are preventing me from using this at all. Is there a way around this?

I’ve also tried using Cannon, but from what I’ve read it’s currently outdated. I don’t know if this would cause any issues with it being outdated. I started using “cannon-es” which is the updated version, but I also get an error when using that:
TypeError: this.world.add is not a function

According to this Github Issue:

It looks like this might have been resolved but I still get the issue using this code:
(using the cannon-es NPM package)
`import * as CANNON from “cannon-es”;

async CreatePhysics(): Promise {
//tried using this from the example in the Github issue
// window.CANNON = CANNON;

this.scene.enablePhysics(

  new Vector3(0, -9.81, 0),

  new CannonJSPlugin(null, null, CANNON)

);

}

`

I’m going to try using the outdated cannon NPM package, but if someone can tell me what I’m doing wrong here and how to use an updated physics engine I would greatly appreciate it. Thanks.

For me, I am using Ammo.js typed package to get the typescript types properly, package.json:

"ammojs-typed": "^1.0.6"

Then I initialize it in my async function:

import Ammo from 'ammojs-typed'
const ammo = await Ammo()
let physics: AmmoJSPlugin = new AmmoJSPlugin(true, ammo)
scene.enablePhysics(new Vector3(0, -10, 0), physics)
4 Likes

Thank you, I wasn’t aware of the typed version of ammojs. I just tried it myself and it works, marked solution.

2 Likes