Search code examples
javascriptreactjsthree.jsreact-three-fiberreact-three-drei

Moving 3d Object in three JS by BUTTON


I'm a beginner at Three JS and need some help with my code. Please, Could you help me for a second?

1| Button1 "increase + 1". After Clicking Button 1, ROOM1 will move to ROOM2 Location and so forth. Room8 will move to ROOM1 position.

2| Button2 "increase + 2". After Clicking Button 2, ROOM1 will move to ROOM3 Location and so forth. Room8 will move to ROOM2 position.

Here's an example of what I mean: enter image description here

This is my Code in Sandbox.

https://codesandbox.io/s/threejs-code-3rlk8b?file=/src/components/PartOne.js

Please help me.

Thank You So much for Your Precious Time

I'm expecting the solution that how can I use a click button and move my 3d Objects(room)


Solution

  • Using react state changes i did this solution.

    First, you have positioned every room at a fixed point. You need to rotate the rooms which means you need to change their positions.

    For this, i changed the fixed points in Room components to take it from props.

    Example: for room8,

    export function Room8({position,...props}) {
      const { nodes, materials } = useGLTF('./models/room8.glb')
      return (
        <group castShadow receiveShadow {...props} dispose={null}>
          <group castShadow receiveShadow position={position} rotation={[Math.PI, 0, Math.PI]}>
        ...your code
        </group>
      </group>
      )
    }
    

    do this for all rooms.

    Then add those positions as array in your PartOne.js

    const positions= useMemo(()=>[
        [0,0,0],
        [-4, -2.7, 0],
        [-0.5, -2.7, 3.6],
        [-7.6, -5.5, 0],
        [-4.5, -5.5, 3.6],
        [-0.4, -5.5, 7.2],
        [-7.6, -8.3, 3.55],
        [-4, -8.3, 7.2]
    ]);
    

    In PartOne.js

    add a state to have your rooms in order.

    const [rooms,setRooms]=useState(
        [RoomOne,Room2,Room3,Room4,Room5,Room6,Room7,Room8]
    );
    

    add your button and rotate the room array,

    <button onClick={()=>{
       let arr=[...rooms];
       arr.unshift(arr.pop())
       console.log("arr::",arr)
       setRooms(arr)
    }}>Rotate +1</button>
    

    render the state rooms inside canvas,

    <Canvas shadows camera={{ fov:70, position: [0,0,30] }} >
        <Suspense fallback={null}  >
           <ambientLight intensity={0.3} />
           <directionalLight castShadow receiveShadow intensity={2} position={[80,80,80]} />
         {rooms.map((room,roomIndex)=>room({position:positions[roomIndex]}))}
           <ContactShadows />
        </Suspense>
        <OrbitControls enablePan={true} enableZoom={true} enableRotate={true} />
     </Canvas>
    

    Adding the sandbox with above changes for your reference,

    Code Sandbox