Here’s an example using cannonjs in a web worker: https://github.com/schteppe/cannon.js/blob/master/examples/worker.html
The gist is that the worker writes all of the objects’ positions and rotations into a (Float32Array) array
and sends array.buffer
back to the main thread on each frame. If you have interactive elements (like VR controllers) this becomes a tradeoff, as collisions won’t feel as snappy when physics aren’t synced to VR rendering unless you use some tricks to update earlier. In my opinion the worker only becomes necessary when you have enough objects being simulated that it cuts into your FPS.
I’ve used CannonJS — it’s probably the best documented, which makes it easier to get started with, but isn’t maintained these days. AmmoJS is compiled from the classic Bullet engine, so that’s fully featured and stable, but quite a large library. Oimo.js is also worth a look, although I haven’t tried it.