R3f <ContactShadows /> that moves with camera

Hi, I am trying to have a <ContactShadow /> move with the camera, so that - when my character move - an area large enough to cover the camera frustum as projected on the ground will have shadows, without needing a huge shadow map.

However, as I move the <ContactShadow />, I cannot seem to get the projection correct. I have tried updating position, target, using lookAt, calling updateMatrix, etc, but nothing works.

The behavior I am experiencing - which is a bit weird to me - is that the shadow projection moves in the opposite direction of the camera/player, by a factor of 2 or so. See the attached video.

As stated, I’ve tried different solutions, here is one:

const Lighting = () => {
  const [pp] = useAtom(playerPositionAtom)

  const contactShadowsPosition: [number, number, number] = useMemo(() => [pp[0], 0.1, pp[2]], [pp])

  return (
    <>
      <Environment preset="forest" />

      <ContactShadows
        position={contactShadowsPosition}
        near={-0.1}
        scale={50}
        resolution={2048}
        opacity={0.25}
        blur={0.025}
      />
    </>
  )
}

i think it would require changes to the component. it was based on a threejs official example but this one wasn’t made for movement. could you copy the component into your local project and maybe you find a fix, it would be much appreciated of you add it back as a PR again.

Thanks @drcmda I will give it a shot!

This can be reduced even further to

<ContactShadows
  position={[1,0.1,1]}
  near={-0.1}
  scale={100}
  resolution={2048}
  opacity={0.25}
  blur={0.025}
/>

so it seems translations are not handled at all, or at least in a way that makes sense IMO.

By adding some helpers, I can see that the shadow camera and the target geometry is updated as it should, so I guess it is the projection itself that is not updated, some how.

This is a bit out of my comfort zone, but I’ll keep looking and see what I can find.

I gave this a little more time, but at the end of the day, I do not really have the time to spend chasing this rabbit right now.

I decided to instead use a directional light as a child of the object, which “just works”. It has the unintended consequence of adding more light to the scene, but I can work around that, so I will not proceed with this.

But thanks very much for your input @drcmda