How can I use Raycaster with react three fiber?

I want to detect clicks outside of the model that’s why I need raycaster to use. When I click out of the model I need to reset the camera. I found documention for threejs but dont know how can I do that with react three fiber?

it has pointer events inbuilt, you normally don’t need raycasting. if you do need want to raycast yourself, use it in the exact same way as you always would, that goes for everything else, too — three-fiber really is only three.

anyway:

<mesh onClick={() => console.log("you clicked me")} ... />
<mesh onPointerMissed={() => console.log("you clicked, but not me")} ... />
<Canvas onPointerMissed={() => console.log("you clicked, but hit nothing at all")} ... />

you can also have events at the group or scene level since pointer events are modelled after the dom, they can bubble up. that means you can group or wrap multiple meshes and put handlers on the group. you get the hit object as event.object and the source of the event (the group) as event.eventObject

const { scene } = useGLTF(url)
return <primitive object={scene} onClick={(e) => console.log("you clicked", e.object.name)} />

here is a real world example of pointers being processed at the group-level as well as clicks outside Shoe configurator - CodeSandbox

1 Like

This really helped me a lot. My issue is solved. Thank you so much

How do i select only one mesh with this approach. onClick is getting called more than once at times when we click only once

<group onClick={e => console.log(e)}>
  <mesh geometry={foo} />
  <mesh geometry={bar} />
  <mesh geometry={baz} />
</group>

if foo, bar, baz are overlapping or arranged in a way in which one raycast would pierce all three the onclick must fire three times, and it will.

<group onClick={e => {
  e.stopPropagation()
  console.log(e)
}}>

now the first mesh that is closest to the pointer wins.

events are modelled after dom events and work similar. it’s fully documented here React Three Fiber Documentation

3 Likes

Beautiful clarity in your answers. That helped me a lot in my current issue, thank you so much.