Instanced Grid

Thousands of lightweight instances arranged in a grid.

What this code does

- InstancedMesh: renders 400 cubes (20x20) with a single draw call for performance.
- Matrix4: each instance has a transformation matrix for position/rotation/scale.
- Performance: dramatically faster than creating 400 individual Mesh objects.
- Random Heights: each cube positioned at random Y height for visual variety.
- DirectionalLight: provides consistent lighting across all instances.

JavaScript (plain)

import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'

const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000)
camera.position.set(3, 3, 3)
camera.lookAt(0, 0, 0)

const renderer = new THREE.WebGLRenderer({ antialias: true })
renderer.setSize(width, height)

document.querySelector('#app').appendChild(renderer.domElement)

const controls = new OrbitControls(camera, renderer.domElement)
controls.target.set(0, 0, 0)
controls.update()

const geometry = new THREE.BoxGeometry(0.1, 0.1, 0.1)
const material = new THREE.MeshStandardMaterial({ color: 0x00aaff })
const count = 20 * 20
const mesh = new THREE.InstancedMesh(geometry, material, count)
let i = 0
for (let x = -1; x < 1; x += 0.1) {
  for (let z = -1; z < 1; z += 0.1) {
    const m = new THREE.Matrix4()
    m.setPosition(x * 2, Math.random() * 0.5, z * 2)
    mesh.setMatrixAt(i++, m)
  }
}
scene.add(mesh)

const light = new THREE.DirectionalLight(0xffffff, 1)
light.position.set(2, 4, 2)
scene.add(light)

function animate() {
  requestAnimationFrame(animate)
  controls.update()
  renderer.render(scene, camera)
}
animate()