pmndrs / react-three-fiber

🇨🇭 A React renderer for Three.js
https://docs.pmnd.rs/react-three-fiber
MIT License
27.62k stars 1.6k forks source link

canvas "onCreated" callback does not work #3284

Closed pedroalmeida415 closed 3 months ago

pedroalmeida415 commented 5 months ago

When setting up my canvas, I tried to assign a default value to the Pointer property like so:


onCreated={(state) => {
    state.pointer.set(0, 1) // desired initial position
    state.raycaster.setFromCamera(state.pointer, state.camera)
    console.log(state.pointer) // Vector2 { "x": 0, "y": 1} -- values are correctly set
}}

But when getting the state from inside one of my components, the values haven't changed:


  const pointer = useThree((state) => state.pointer)
  console.log(pointer) // Vector2 { "x": 0, "y": 0} -- wrong values outside useFrame, from the very first render

.
.
.

  const uMouseVec = new THREE.Vector2()

  useFrame((state, delta) => {
    console.log(state.pointer) // Vector2 { "x": 0, "y": 0} -- wrong values inside useFrame as well
    state.raycaster.setFromCamera(state.pointer, state.camera)
    const intersects = state.raycaster.intersectObject(planeArea.current)

    if (intersects.length > 0) {
      variable.material.uniforms.uMouse.value = uMouseVec.set(intersects[0].point.x, intersects[0].point.y)
    }
.
.
.
  })

Calling pointer.set(1,1) inside the component correctly changes the values, but I can't understand why it doesn't work to set the default value on the onCreated callback, I thought it's whole purpose was to do things just like this.

If I'm doing something wrong, please let me know! Thanks in advance

pedroalmeida415 commented 3 months ago

UPDATE

Tried updating the state itself, but that didn't work either:

onCreated={(state) => {
  state.set({
    pointer: new Vector2(0, 1),
  })
}}
pedroalmeida415 commented 3 months ago

Updating the library to the latest version solved the problem!