I am currently working on a project using react-three-fiber to create a scene. However, I am facing an issue with placing 3D objects at different random positions. I tried using a for loop inside useFrame to set random positions, but this causes the particles to repeatedly move to random positions. I want these positions to be randomized only during initialization and then move the entire mesh. When I try to use the for loop just before useFrame, I encounter an error - "Cannot read property 'setMatrixAt' of undefined". PS: I am attempting to recreate a scene similar to -
import * as THREE from 'three'
import ReactDOM from 'react-dom'
import React, { useRef, useMemo, useState, useEffect } from 'react'
import { Canvas, useFrame } from 'react-three-fiber'
import Effects from './Effects'
import './styles.css'
const tempObject = new THREE.Object3D()
function Boxes({count}) {
const ref = useRef()
const previous = useRef()
const particles = useMemo(() => {
const temp = []
useFrame(state => {
const time = state.clock.getElapsedTime()
ref.current.rotation.x += 0.00000
ref.current.rotation.y += 0.00000
let i = 0
for (let x = 0; x < count; x++){
const id = i++
tempObject.position.set(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5 ).normalize()
tempObject.position.multiplyScalar( Math.random() * 40 )
tempObject.rotation.set( Math.random() * 2, Math.random() * 2, Math.random() * 2 )
tempObject.updateMatrix()
ref.current.setMatrixAt(id, tempObject.matrix)
}
ref.current.instanceMatrix.needsUpdate = true
})
return (
<instancedMesh ref={ref} args={[null, null, count]} >;
<sphereBufferGeometry attach="geometry" args={[1, 4, 4]}/>
<meshPhongMaterial attach="material" color="#ffffff" flatShading ="true"/>
</instancedMesh>
)
}
ReactDOM.render(
<Canvas
gl={{ antialias: false, alpha: false }}
camera={{ position: [0, 0, 400], near: 5, far: 1000 }}
onCreated={({ gl }) => gl.setClearColor('pink')}>
<ambientLight intensity={1.1} color="#222222" />
<directionalLight color="#ffffff" position={[1, 1, 1]} />
<Boxes count={1000}/>
<Effects />
</Canvas>,
document.getElementById('root')
)