0

In grid.js

import { Box, TransformControls } from "@react-three/drei";
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react";

const RectGrid=()=> {

    const boxRef1 = useRef();
        const boxRef2 = useRef();
    const matRef1 = useRef();
        const matRef2 = useRef()

    const [tColor, setCol] = useState("blue");
    const [op, setOp] = useState(0.5);

        
                  boxes.push(
                <Box
                    key={`${row}-${col}`}
                    position={[0, 0, 0]}
                    scale={[0.5, 0.5, 0.5]}
                    ref={boxRef1}
                >
                    <meshBasicMaterial
                        ref={matRef1}
                        color={tColor}
                        transparent
                        opacity={op}
                    />
                </Box>
            );

                  boxes.push(
                <Box
                    key={`${row}-${col}`}
                    position={[1, 0, 0]}
                    scale={[0.5, 0.5, 0.5]}
                    ref={boxRef2}
                >
                    <meshBasicMaterial
                        ref={matRef2}
                        color={tColor}
                        transparent
                        opacity={op}
                    />
                </Box>
            );
    // Return the boxes as a group
    return (<>{boxes}</>);
});

export default RectGrid;

In scene.js:

const [selectedObject, setSelectedObject] = useState(null);

useFrame(() => {
        raycaster.setFromCamera(mouse, camera);
        // Find all intersections between the raycaster and the scene
        const intersects = raycaster.intersectObjects(scene.children, true);
        //Check if the mouse is hovering over the box
        if (intersects.length > 0) {
            for (var i = 0; i < intersects.length; i++) {
                if (intersects[i].object.name.startsWith("MyBox")) {
                    const curr = intersects[i].object;
                    setSelectedObject(curr);

                }
            }
        }
    });

    return (
        <>
                        <button>Change color to red</button>
            <RectGrid name="MyBox1" ref={GridRef1}></RectGrid>
            <RectGrid name="MyBox2" ref={GridRef1}></RectGrd> 
        </>
    );

I want to modify the color and other properties of both the boxes of one particular grid simultaneously which is selected by the user. But when I use raycaster, the ref I get is of individual box. How can I modify the properties of both the boxes of one particular RectGrid at once?

  • Can't you just pass the color as a prop to the child component ? Otherwise you'll need to forward the child ref to the parent component => https://react.dev/reference/react/forwardRef No need to cast rays yourself every frame, R3F takes care of this for you => https://docs.pmnd.rs/react-three-fiber/api/events – Remi Apr 11 '23 at 13:40

0 Answers0