1

I have a react-three-scene where this line joins two cubes. I can move the cubes using TransformControls.

<Line
points={[
 [pos1.x, pos1.y, pos1.z],
 [pos2.x, pos2.y, pos2.z],
]}
 ref={addToPathRefs}
/>

I want that the points of this line dynamically modify as I move the cubes. I cannot use state because there can be any number of cubes in that scene.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174

1 Answers1

0
    import React, { useEffect, useRef } from 'react';
import { Line } from 'react-three-fiber';
import { TransformControls } from 'three/examples/jsm/controls/TransformControls';

const MyScene = () => {
  const cubes = useRef([]);
  const lineRef = useRef();

  useEffect(() => {
    const line = lineRef.current;

    const updateLinePoints = () => {
      const points = cubes.current.map((cube) => cube.position.toArray()).flat();
      line.geometry.setFromPoints(points);
      line.geometry.verticesNeedUpdate = true;
    };

    const transformControls = new TransformControls(/* camera instance */);
    cubes.current.forEach((cube) => transformControls.attach(cube));
    /* Add event listeners or controls to handle cube movements with TransformControls */

    // Update line points whenever cubes are moved
    transformControls.addEventListener('change', updateLinePoints);

    return () => {
      // Cleanup listeners or controls if necessary
      transformControls.dispose();
    };
  }, []);

  return (
    <>
      {/* Render cubes */}
      {cubes.current.map((cube, index) => (
        <mesh key={index} ref={(ref) => (cubes.current[index] = ref)}>
          {/* Cube geometry */}
        </mesh>
      ))}

      <Line
        points={[]} // Initial empty points, will be updated dynamically
        ref={lineRef}
      />
    </>
  );
};

export default MyScene;
lareb
  • 98
  • 6
  • Both of the things did not work for me 1) When I kept the points={[]} empty, I got this error "Invalid typed array length: -6 RangeError: Invalid typed array length: -6 at new Float32Array (" 2) Secondly the points are not changing – Samir Kumar Patro Jun 21 '23 at 09:04