Sync physics body position and rotation with bone / mesh with Havok physics plugin

I don’t see any materials with this solution on the internet except for only 1 and it’s for setting the body position. The method in the babylon.js docs seem to make the bodies not trigger collision observable properly (at least from my testing)… So I’m posting this here in case anyone needs this in the future.

To set position: use HP_Body_SetPosition
To set rotation: use HP_Body_SetOrientation
Can be found in the package @babylonjs/havok at /lib/esm/HavokPhysics_es.js

Example code snippet (Typescript):

this._scene.onBeforeRenderObservable.add(() => {
          const plugin = this.scene.getPhysicsEngine()?.getPhysicsPlugin();
          if (!plugin) return;
          (plugin as HavokPlugin)._hknp.HP_Body_SetPosition(body._pluginData.hpBodyId, [
            bone.getPosition(1, this._root).x,
            bone.getPosition(1, this._root).y,
            bone.getPosition(1, this._root).z,
          ]);

          (plugin as HavokPlugin)._hknp.HP_Body_SetOrientation(body._pluginData.hpBodyId, [
            bone.getRotationQuaternion(1, this._root).x,
            bone.getRotationQuaternion(1, this._root).y,
            bone.getRotationQuaternion(1, this._root).z,
            bone.getRotationQuaternion(1, this._root).w,
          ]);
        })

Hope this helps!

2 Likes

Neat! I didn’t realize HP_Body_SetPosition() and HP_Body_SetOrientation() existed, since they aren’t in the .d.ts types

1 Like