Create InstancedEntity
Each instance can automatically create an associated InstancedEntity
.
This provides a simple API to access and modify instance properties, as shown below:
iMesh.instances[index].position.random();iMesh.instances[index].rotateX(Math.PI);iMesh.instances[index].updateMatrix(); // Required after transformations
To enable entity creation, set the createEntities
flag in the constructor parameters:
const iMesh = new InstancedMesh2(geo, mat, { createEntities: true });
Example
This example demonstrates how the instances array can be used to animate instances easily:
import { InstancedMesh2 } from '@three.ez/instanced-mesh';import { MeshStandardMaterial, TorusKnotGeometry } from 'three';
const geo = new TorusKnotGeometry();const mat = new MeshStandardMaterial()export const torusKnots = new InstancedMesh2(geo, mat, { createEntities: true });
torusKnots.addInstances(9, (obj, index) => { obj.position.x = (index % 3 - 1) * 5; obj.position.y = (Math.trunc(index / 3) - 1) * 5; obj.quaternion.random(); obj.color = Math.random() * 0xffffff;});
torusKnots.on('animate', (e) => { for (const instance of torusKnots.instances) { instance.rotateZ(e.delta); instance.updateMatrix(); }});
import { Scene, DirectionalLight, AmbientLight } from 'three';import { Main, PerspectiveCameraAuto } from '@three.ez/main';import { OrbitControls } from 'three/addons/controls/OrbitControls.js';import { torusKnots } from './app.js';
const main = new Main();const camera = new PerspectiveCameraAuto().translateZ(20);const scene = new Scene().add(torusKnots);main.createView({ scene, camera });
const controls = new OrbitControls(camera, main.renderer.domElement);controls.update();
const ambientLight = new AmbientLight('white', 0.8);scene.add(ambientLight);
const dirLight = new DirectionalLight('white', 2);dirLight.position.set(0.5, 0.866, 0);camera.add(dirLight);