Hello,
I’ve recently started working with instanced mesh and I’m having a little trouble seeing how it works. I would like to remove cubes after their “hp” reaches 0. i.e. make invisible remove all their characteristics like hitbox etc…
I have tested remove and invisible but neither function seems to work.
import * as THREE from "three"
import React, { useRef, useMemo, useState, useEffect } from "react"
import { Canvas, useFrame } from "@react-three/fiber"
import niceColors from "nice-color-palettes"
const squareLen = 3
const size = squareLen * squareLen * squareLen
const tempObject = new THREE.Object3D()
const tempColor = new THREE.Color()
const data = Array.from({ length: size }, () => ({ color: niceColors[17][Math.floor(Math.random() * 5)], hp: 5 }))
export const TheCube = (props) => {
const [hovered, set] = useState()
const colorArray = useMemo(() => Float32Array.from(new Array(size).fill().flatMap((_, i) => tempColor.set(data[i].color).toArray())), [])
const meshRef = useRef()
const prevRef = useRef()
useFrame((state) => {
let i = 0
for (let x = 0; x < squareLen; x++)
for (let y = 0; y < squareLen; y++)
for (let z = 0; z < squareLen; z++) {
const id = i++
if (data[id].hp <= 0) {
tempObject.visible = false
continue
}
if (id === hovered) {
data[id].hp = data[id].hp - 1
console.log(data[id].hp)
set(undefined)
}
tempObject.position.set(10 + x * 10, 5 + y * 10, 10 + z * 10)
tempColor.set(id === hovered ? "white" : data[id].color).toArray(colorArray, id * 3)
meshRef.current.geometry.attributes.color.needsUpdate = true
tempObject.updateMatrix()
meshRef.current.setMatrixAt(id, tempObject.matrix)
}
meshRef.current.instanceMatrix.needsUpdate = true
})
return (
<instancedMesh ref={meshRef} args={[null, null, size]} onClick={(e) => set(e.instanceId)} onPointerUp={(e) => set(undefined)}>
<boxGeometry args={[10, 10, 10]}>
<instancedBufferAttribute attachObject={["attributes", "color"]} args={[colorArray, 3]} />
</boxGeometry>
<meshPhongMaterial vertexColors={THREE.VertexColors} />
</instancedMesh>
)
}