beewest
beewest

Reputation: 4856

Create instanced triangles in react-three/fiber

I can create a triangle with BufferGeometry where array=new Float32Array([0, 20, 0, 0, 0, 0, 20, 0, 0]);

<mesh>
      <bufferGeometry attach="geometry">
        <bufferAttribute
          attachObject={["attributes", "position"]}
          count={3}
          array={array}
          itemSize={3}
        />
      </bufferGeometry>
      <meshBasicMaterial
        attach="material"
        color="#5243aa"
        wireframe={false}
        side={THREE.DoubleSide}
      />
    </mesh>

Now I want to create 1 triangle using InstancedMesh. However it doesn't work as expeced.

<instancedMesh ref={meshRef} args={[null as any, null as any, 1]}>
        <bufferGeometry attach="geometry">
          <bufferAttribute
            attachObject={["attributes", "position"]}
            count={3}
            array={position}
            itemSize={3}
          />
        </bufferGeometry>
        <meshBasicMaterial
          attach="material"
          color="#5243aa"
          wireframe={false}
          side={THREE.DoubleSide}
        />
      </instancedMesh>

Any idea please?

Upvotes: 1

Views: 2229

Answers (1)

beewest
beewest

Reputation: 4856

Declare an instanced mesh where vertices=[x1,y1,z1,...] is the coordinates of the triangle:

<instancedMesh ref={meshRef} args={[null as any, null as any, 10]}>
        <bufferGeometry attach="geometry">
          <bufferAttribute
            attachObject={["attributes", "position"]}
            args={[vertices, 3]}
          />
        </bufferGeometry>
        <meshBasicMaterial attach="material" side={THREE.DoubleSide} />
      </instancedMesh>

Update each instance's position and color:

useEffect(() => {
    if (meshRef === null) return;
    if (meshRef.current === null) return;

    const mesh: any = meshRef.current;

    for (let i = 0; i < 10; i++) {
      //position
      tempObject.position.set(
        100 * Math.random(),
        100 * Math.random(),
        100 * Math.random()
      );
      tempObject.updateMatrix();
      mesh.setMatrixAt(i, tempObject.matrix);

      // color
      mesh.setColorAt(
        i,
        tempColor.setRGB(Math.random(), Math.random(), Math.random())
      );
    }
  });

The result:

enter image description here

Upvotes: 1

Related Questions