Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

javascript - How to access controls instance in react-three-fiber?

Is there any way to access the controls instance of the scene in react-three-fiber?

I know it can be accesed using a ref like:

import { useFrame } from 'react-three-fiber'

const controls = useRef()
useFrame(state => controls.current.update())
return <orbitControls ref={controls} />

But I am looking for some kind of global access like:

    const { 
        gl,         // WebGL renderer
        scene,      // Default scene
        camera,     // Default camera
    } = useThree()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't think you can do it out of the box.

One way to achieve something like the useThree example, is to store the controls ref in a Context, and then you should be able to use it consuming that Context in any descendant of the component tree.

For example (keep in mind I didn't test this code):

const ControlsContext = createContext()

const ControlsContainer = ({ children }) => {
  const controls = useRef()
  return (
    <ControlsContext.Provider value={{ controls: controls.current }}>
      <orbitControls ref={controls} />
      {children}
    </ControlsContext.Provider>
  )
}

const YourComponent = () => {
  const { controls } = useContext(ControlsContext)
  // do whatever you need, but remember to check if it's defined
}

const App = () => (
  <ControlsContainer>
    <YourComponent />
  </ControlsContainer>
)

However I don't think this is a good practice. You probably want to keep all your controller code in one component. And in the case you need to share it to another component you could simply pass it down in a prop.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...