I am currently using react-three-fiber to make scene but I don't know how to put 3D objects at different random positions. I have used a for loop inside useFrame to have different random positions, but as this will render every time, particles will just move to random position again. But I want these positions to be random only at intialization and then just move the whole mesh. But if I use for loop just before the useframe it is giving error-"Cannot read property 'setMatrixAt' of undefined". PS- I am just tring to recreate -https://threejs.org/examples/?q=postprocessing#webgl_postprocessing
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')
)