How Do You Create Points Using Three Js and React-Three-Fibre

I am using React, Three JS, and React-Three-Fibre

I want to create an array of 100 Points with random colors, position and sizes. I am confused with how to go about it, I would like to accomplish it by pre defining buffer arrays, then in some loop each point will be assigned color, position and size from the buffers.

// Buffers
    let positionsBuffer = new Float32Array([[0, 0, 0], [3, 3, 3], [6, 6, 6]] )
    let colorsBuffer = new Float32Array([[92, 123, 23], [123, 12, 233], [23, 98, 198]]) 
    let sizesBuffer = new Float32Array([[1], [2], [3]])

return (
        <mesh
            position={[position_x, position_y, position_z]}
            ref={ref}
            scale={clicked ? 1.5 : 1}
            onClick={() => setClicked(!clicked)}
            onPointerOver={() => setHovered(true)}
            onPointerOut={() => setHovered(false)}
        >
            <Points positions={positionsBuffer} colors={colorsBuffer} sizes={sizesBuffer}>
                <pointsMaterial />
            </Points>
        </mesh>
    )

If for every buffer I just have 1 item let positionsBuffer = new Float32Array([3, 3, 3]) I will be able to place a point. If the buffer arrays contain multiple items, how do I go about rendering a point for every item in the buffer arrays?

1 Answer

I can give you my example, hopefully, it will help.

const particlesCount = 100;
const particlePositions = new Float32Array(particlesCount * 3);

for (let i = 0; i < particlesCount; i++) {
  const i3 = i * 3;

  particlePositions[i3] = Math.random();
  particlePositions[i3 + 1] = Math.random();
  particlePositions[i3 + 2] = Math.random();
}

export const Particles = () => {
  return (
    <points>
      <bufferGeometry>
        <bufferAttribute
          attach='attributes-position'
          count={particlesCount}
          itemSize={3}
          array={particlePositions}
        />
      </bufferGeometry>
      <pointsMaterial
        size={0.04}
        color={colors.materialColor}
        transparent
      />
    </points>
  );
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest