Hello!
I want to make a hybrid physics optimization system that converts sleeping physics bodies into (ISM) instances, then restores the instances hit by a character trace back to simulated physics bodies.
I m not sure if my current approach is the best way to implement this system because sometimes it ends up spawning more simulated physics objects than there are ISM instances…
For example, in the video you can see 20 simulated physics objects being converted into ISM instances once they go to sleep.
So when I move the character around and trace/hit some of the instances more aggressively, the system sometimes spawns additional simulated physics objects. So the result will be 22 simulated physics objects even though there were originally only 20 instances
I don t know how to fix this or if there is a better method to use
the count drift means your convert/restore is not idempotent: a second restore fires for an instance that was already restored, or two traces hit the same instance in one frame and each one spawns. three things to tighten:
make the registry authoritative. keep a map: instance index to saved state (transform, velocity, any data). converting removes/creates entries only through functions that check the map first; restoring consumes the entry and deletes the key BEFORE spawning the actor. if the key is gone, the restore is a duplicate and gets ignored. that alone kills the phantom spawns.
remember RemoveInstance shifts indices. after removing instance 5, every instance above it moves down one and your map keys are now wrong, which is exactly how you end up restoring the wrong instance twice. either remove from the highest index downward, swap-remove the last instance into the freed slot and update the map, or rebuild the whole ISM from the map when the set changes.
honestly, do not destroy and respawn the sim bodies at all. pool them: when a body sleeps, do not destroy it. disable its tick and collision (or move it far away), add an ISM instance at its transform, and keep the actor in a pool. when an instance is hit, find the map entry, remove the instance, re-enable the pooled actor at that transform and wake it. spawn/destroy is where your count leaks from, pooling makes it impossible by construction, and it is much cheaper.
with a map-guarded restore plus pooled actors, the total number of physical objects stays exactly constant.