Moving meshes manually with physics enabled

What do you think of this? Is there a better method?

I move meshes manually all the time with physics enabled. The advice on the forums is consistent:

disable disablePrestep on the physics body right before you want to change a transform on the transformNode. If it is a one time assignment, enable it again in the next frame or so (performance).

Keeping track of which meshes need to re-disable PreStep after the current frame isn’t straightforward. How about something like this?

const disablePreStepArray = Array(); // make sure this is available to functions below

function physicsBodyEnableUpdateTransform(body) {
    body.disablePreStep = false;
    disablePreStepArray.push(body);
    if (disablePreStepArray.length == 1) {
        // add observer once
        scene.onAfterPhysicsObservable.addOnce(disablePreStepObserver); // need access to scene
    }
}
function disablePreStepObserver () {
    if (disablePreStepArray.length){
        disablePreStepArray.forEach((body)=>body.disablePreStep=true);
        disablePreStepArray.length = 0;
    }
}

So instead of taking the performance hit of disabled PreStep all the time

mesh.physicsBody.disablePreStep = true;

Do this instead

physicsBodyEnableUpdateTransform(mesh.physicsBody);

Then the functions above take care of setting disablePreStep back to true, one time, and completely remove the observable to get back any performance impact.

disablePreStep was introduced to disable unnecessary updates. It’s find for most cases and in particular for heavily instanced meshes.
If you have only a few objects that need pre-step, I don’t think enable/disable prestep will make a huge difference and it might make your code more complex.
How many objects needs prestep toggling?

1 Like

This is the piece of information I was missing. For my current scene, less than a hundred with vertices per object at the extreme getting to 50000.