Using AmmoJS with Babylon

This is an emscripten issue that I hope they will resolve.
Short explanation - when running as es module, you don’t have the global context (when running functions in a module. i.e. - this is undefined). hence - it is not possible to assign anything to the global namespace. but emscripten is still trying to do it. and it fails.

fun fun fun!

The solution is simple! :slight_smile:

First import ammo:

import ammo from 'ammojs-typed';

then, in your scene init function use this:

const ImportedAmmo = await ammo.call({});
scene01.enablePhysics(new Vector3(0, -9.81, 0), new AmmoJSPlugin(true, ImportedAmmo));

Setting the context in which the ammo function is called is enough. And - it works:

Avoid polluting the global namespace, avoid importing using different mechanisms. Stick with vite and es modules - this is a wonderful way to get your app performing wonderfully, loading fast, and compiling even faster :slight_smile:

2 Likes