Skip to content

Animate Instances

Animate one instance

If an array of instances has been created, it’s possible to update an instance in this way:

iMesh.instances[index].position.random();
iMesh.instances[index].rotateX(Math.PI);
iMesh.instances[index].updateMatrix(); // Required after transformations

Animate multiple instances with for loop

If an array of instances has been created, it’s possible to update an instance in this way:

for (const instance of iMesh.instances) {
if (instance.active) { // if isn't removed
instance.position.x += 0.1;
instance.updateMatrixPosition();
}
}

Animate all instances using updateInstances

This is the recommended method.
This method iterates over all active instances and automatically calls the updateMatrix method.

this.updateInstances((obj) => {
instance.scale.x += 0.1;
});

Example

import { InstancedMesh2, type InstancedMesh2Params as Params } from '@three.ez/instanced-mesh';
import { MeshStandardMaterial, TorusKnotGeometry } from 'three';
const geo = new TorusKnotGeometry();
const mat = new MeshStandardMaterial()
const options: Params = { createEntities: true };
export const torusKnots = new InstancedMesh2(geo, mat, options);
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) => {
torusKnots.updateInstances((instance) => {
instance.rotateZ(e.delta);
});
});
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);