brianzinn / react-babylonjs

React for Babylon 3D engine
https://brianzinn.github.io/react-babylonjs/
822 stars 105 forks source link

how can i get the scene instance in this with2DUI example ? #228

Closed QMangoJ closed 2 years ago

QMangoJ commented 2 years ago
截屏2022-07-16 下午5 01 58

I want to show inspector like this code Scene.debugLayer.show()

brianzinn commented 2 years ago

hi @QMangoJ One way would be to make a component like this:

import { useScene } from 'react-babylonjs';
import "@babylonjs/inspector";

// This must be placed *inside* <Scene>...</Scene> for hook to work.
export const Inspector = ({show}) => {
  const scene = useScene();

  if (show) {
      scene.debugLayer.show();
  } else {
      scene.debugLayer.hide();
  }
  return null;
};

Then in your calling code:

this.state = {
  plane: undefined,
  ....
  // add this to your state
  showInspector: false;
}

// update event listener to update the state
openBtn.addEventListener('click', () => {
  this.setState((state) => ({
        ...state,
        showInspector: true // !state.showInspector to toggle
      }));
})

// in your scene with2DUI you need to import the Inspector component and then load it on your page.

return (
   <Engine ...>
      <Scene ..>
         <Inspector show={state.showInspector} />
         ...
    </Scene>
  </Engine>
)

Having said all of that - the code would be a lot cleaner with hooks. The example project you are looking at is really overdue for an update.

QMangoJ commented 2 years ago
         <Inspector show={state.showInspector} />

thank u very much. I got it! And i wonder ask a question that how to implement tag like or with react frame? use createContext and react-reconciler? I want to implement a UI frame with react and babylonjs by myself. I'm looking forward your reply.

brianzinn commented 2 years ago

@QMangoJ It sounds like you want to integrate a UI in React (with DOM) and have babylonj.js as part of a larger application. I would look at a library to manage state like zustand (https://github.com/pmndrs/zustand).

If you use createContext then there are issues crossing render boundaries. https://github.com/brianzinn/react-babylonjs/blob/master/packages/storybook/stories/babylonjs/Basic/contextBridge.stories.js

Zustand does not have the createContext issues with crossing render boundaries, so does not need the workaround above.

Otherwise your question looks quite broad. Good luck - it looks like your original issues is solved, so I'm going to close out. Open a new issue if something comes up. Cheers.