React scene with cannon lag why?


I have this scene : the principle is as follows: if the yellow cube overtakes the red instances, the green supports underneath disappear, so that the red instances fall.

The problem is that after the red instances have fallen, my yellow cube moves forward with a lot of lag. It seems from my tests that this is due to the displacement in my Support function, but I don’t see how I can change it to get correct performance. Can you help?


Trying to remove the superfluous and adding some monitoring to make it clear that the scene is really struggling as soon as the instances fall, you can clearly see that the yellow cube is jerking forward. Why is this?

you are setting state in a useFrame


Read avoid-setstate-in-loops and then read instead,-just-mutate,-use-deltas


Thanks for the tips, I’ve modified the code accordingly, but I can’t see any improvement, the blue support is still jerky. I don’t understand why, the code is extremely simple.

This fragment is causing jerkiness:

      for (let i = 0; i < numInstance; i++) {
        at(i).position.subscribe((v) => {
          if (posPlayer[0] > v[0] && flagTest) {
            at(i).position.set(-6, 2, i * 2)
            at(i).velocity.set(0, 0, 0)

I have no idea what does subscribe do, but whatever it does, that subscription is done every frame. Should it? When I make it execute only once, the jerkiness disappears.



I cleaned up my codesandbox by deleting all items and keeping only cube instances and support instances. I’m only applying a move to the [0] support instance, but even when I apply the recommendations React Three Fiber Documentation , I can see that the code is rowing like crazy. I’m at a loss… if you could tell me how to implement moves and checks on instances, that would be great.

Next thing you should do is update all your dependencies.

You are using a very old @react-three/cannon
And quite old @react-three/fiber & drei

Press the refresh icon when you hover over the dependency in the list

And if you remove frameloop="demand" it will fix r3f-perf.

This is not the full fix. Just some things that will help.