pmndrs / use-cannon

👋💣 physics based hooks for @react-three/fiber
https://cannon.pmnd.rs
2.78k stars 156 forks source link

Removing bodies with api.subscribe hook enabled causing errors. #115

Closed indiebubbler closed 3 years ago

indiebubbler commented 4 years ago

If you use useEffect(() => {api.velocity.subscribe((p) => (currentVel.current = p))}) on a particular body, there is chance that removing this body from the scene will cause an error and stop physics to work. It's not consistent behavior but it happens each time sooner or later.

Following sandbox adds and removes balls into the scene in 500ms intervals. After 'sometime' it will cause:

TypeError
Y[I] is not a function
eval
https://mu1ie.csb.app/node_modules/use-cannon/dist/Provider-f05cb643.js:54:122
Worker.m.onmessage
https://mu1ie.csb.app/node_modules/use-cannon/dist/Provider-f05cb643.js:54:98

Sandbox: https://codesandbox.io/s/friendly-sinoussi-mu1ie?file=/src/index.js

Removing the api.subscribe line solves the problem.

jak2030 commented 3 years ago

Running into the same issue!

andreivips commented 3 years ago

looks like subscriptions list gets out of sync in worker:

case 'step': { ..... const [uuid, type] = subscriptions[id] // this line gives error: Cannot read property 'position' of undefined let value = bodies[uuid][type] .....

a plain check for current existence ?

indiebubbler commented 3 years ago

Hi, Just heads up to let you all know, that I've updated original sandbox to use latest version of packages (cannon 1.1.1, r3f 6.0.17 etc.) and the error still persists, although it has changed its description slightly. It's the same problem though IMO. Sometimes the error doesn't pop up but the physics becomes stalled anyway.

TypeError
subscriptions[id] is not a function

https://codesandbox.io/s/friendly-sinoussi-mu1ie?file=/src/index.js

David-Beale commented 3 years ago

I've been scratching my head over this all afternoon (I'm trying to use a slider to add/remove objects).

I've added a PR to fix this: https://github.com/pmndrs/use-cannon/pull/195