I am using React Three Fiber. I have a group, and within that group, I have a green cube. On the mesh onClick event, I create a child cube. On the group’s onDoubleClick event, I intend to move the green cube, with the expectation that the green cube will move with all of the group’s child cubes. However, only the green cube moves.
I attempted to use the updateMatrixWorld function, but it doesn’t seem to work either. I have created a CodeSandbox to demonstrate the issue.
import './styles.css'
import React, { useRef, useState, useLayoutEffect, useEffect, useMemo, Suspense, useImperativeHandle, forwardRef } from 'react'
import { Box3, Vector3 } from 'three'
import { useLoader, Canvas, useThree, useFrame } from '@react-three/fiber'
import { Box } from '@react-three/drei'
import * as THREE from 'three'
function Scene() {
const [childCubes, setChildCubes] = useState([])
//const [isAddingChildCube, setIsAddingChildCube] = useState(false);
// Add a child cube to the scene
const addChildCube = () => {
const newChild = {
position: [
Math.random() * 4 - 2, // Random X position
Math.random() * 4 - 2, // Random Y position
Math.random() * 4 - 2 // Random Z position
]
}
setChildCubes([...childCubes, newChild])
}
// Create an array of child cube components
const childCubeComponents = childCubes.map((child, index) => (
<Box key={index} position={child.position} args={[0.2, 0.2, 0.2]} color="red" />
))
const moveAll = (event) => {
const [x, y, z] = event.point.toArray()
const newPosition = new THREE.Vector3(x + 0.5, y + 0.5, 0.5)
event.object.position.copy(newPosition)
event.object.updateMatrixWorld()
}
return (
<group onDoubleClick={moveAll}>
{/* Render child cube components */}
{childCubeComponents}
{/* Clickable 3D Cube as a Button */}
<mesh
position={[0, 0, 0]} // Adjust the position as needed
onClick={addChildCube} // Trigger the addition of child cubes
>
<boxGeometry attach="geometry" args={[0.5, 0.5, 0.5]} />
<meshStandardMaterial attach="material" color="green" />
</mesh>
</group>
)
}
function App() {
return (
<div style={{ width: '100%', height: '100vh' }}>
<Canvas camera={{ position: [0, 0, 5] }}>
<ambientLight />
<pointLight position={[3, 3, 3]} />
<Scene />
</Canvas>
</div>
)
}
export default App