Scene management through js Events (React3F + React-XR)

137 views Asked by At

I'm quite a beginner with JS and I'm trying to use React3F + ReactXR to create some WebXR apps for Hololens 2. I'm actually stuck on how to add elements on demand via JS events (eg. select event).

The intended behavior is to place an object whenever the select event is detected and keep that object in place when the event ends. The next step would be to manage how to create more than one object through this method.

The actual behavior is that whenever the select event is detected, it "keeps activating" the render of the object and you can drag it through the scene until the select event is detected again. Then the object just disappears and this can be repeated at will.

The code:

import React, { useEffect } from 'react'
import { useHitTest,Interactive, XR, Controllers, ARButton, useXREvent, VRButton} from '@react-three/xr'
import { Box, Plane } from '@react-three/drei'
import { Canvas } from '@react-three/fiber'
import * as THREE from 'three'

//App minima que permite la colocacion y el arrastre de elementos mediante ReactXR

const texture = new THREE.TextureLoader().load( "src/assets/img/mona_lisa.png" );

const PictureBoxExample= () => {

  const ref = React.useRef()

  useHitTest((hit) => {
    hit.decompose(ref.current.position, ref.current.rotation, ref.current.scale)
  })

  return <Box ref={ref} args={[0.2, 0.001, 0.35]} > 
          <meshBasicMaterial map={texture} />
          <Box args={[0.2, 0.001, 0.35]} position={[-0.35,0,0]} /* rotation= {ref.current.rotation} */> 
            <meshBasicMaterial color={'green'} />
          </Box> 
         </Box>
}

function HitTestExample() {
  const [active, setActive] = React.useState(false)

  useXREvent('select', () => {
    setActive(!active)
  })

  if (!active) {
    return <></>
  } else {
    return <PictureBoxExample />
  }
}

export function App() {
  return (
    <>
      <ARButton />
      <Canvas> 
        <XR>
          <ambientLight />
          <Controllers />
          <HitTestExample />
        </XR>
      </Canvas>
    </>
  )
}

export default App
0

There are 0 answers