pmndrs / use-cannon

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

Add body existence check in step function #407

Closed alex-shortt closed 4 months ago

alex-shortt commented 1 year ago

Hello - something about my usage seems to be wrong and I'd love some help figuring that out, but an issue regardless of my setup is the error Cannot read properties of undefined (reading 'position') coming from this line. For some reason my body subscriptions are losing values but not disappearing from state. There should definitely be a check there . I'll submit a pr in a second.

As for what may be wrong with my setup, I'm using the Physics component in a separate component, seen here, which upon re-render may be losing internal state.

alex-shortt commented 1 year ago

Submitted a pr here: #408

As for the cause, after looking at the source I can better describe it as unloaded bodies don't seem to remove subscriptions. So it's probably not the Physics component itself that's resetting since it's still aware of the subscriptions, but that the body is being unloaded without the subscriptions being unloaded.

darkopetrovic commented 1 year ago

I've the same error when using api subscription and when objects are removed from the scene. Don't know how but then the api stops working for the other objects too.

alex-shortt commented 1 year ago

yeah i can second this ^ seems to happen when objects are removed from the scene

bjornstar commented 1 year ago

Could you share a reproduction with us then we can be sure to fix it.

alex-shortt commented 1 year ago

@bjornstar the problem seems clear, as pointed out here, subscriptions aren't being removed when the body is removed. am i missing something?

this is my fix in #411: https://github.com/pmndrs/use-cannon/blob/9259f8700ef96e0555381afd4ec96e54e3bf507b/packages/cannon-worker-api/src/worker/index.ts#L48-L52

alex-shortt commented 1 year ago

now fixed in #412

mattblackdev commented 1 year ago

I experienced this when I setup a subscription but did not handle the returned unsubscribe function from subscribe.

So kids, eat your veggies and don't forget to unsub

useEffect(() => { 
  const unsub = api.subscribe(...)
  return unsub 
}, [api])

so it gets called when your component unmounts.