Ada Rose Cannon

Oct 29, 2020

5 min read
This effect is used to make the fish move organically and efficiently in the koi garden demo.

Curve Modifiers in Three.js

My first major PR to Three.js

How it works

const canvas = document.querySelector('canvas');
const context = canvas.getContext( 'webgl2', { antialias: true } );
const renderer = new WebGLRenderer({ canvas, context });
The Koi Garden demo with 300 fish

Using the Three.js Example

3D text duplicated 8 times traveling along two paths.
import { Flow } from "three/examples/jsm/modifiers/CurveModifier.js";const points = [
new Vector3( 1, 0, z: -1 ),
new Vector3( 1, 0, z: 1 ),
new Vector3( -1, 0, z: 1 ),
new Vector3( -1, 0, z: -1 ),
];
const curve = new THREE.CatmullRomCurve3(points);
curve.curveType = "centripetal";
curve.closed = true;
const mesh = // some mesh I made earlier;// You may need to tweak the geometry beforehand to get it to
// Display with the orientation you expect.
mesh.geometry.rotateX( Math.PI );
const flow = new Flow( objectToCurve );
flow.updateCurve( 0, curve );
scene.add( flow.object3D );
import { InstancedFlow } from "three/examples/jsm/modifiers/CurveModifier.js";const material = // some material
const geometry = // some geometry
const curve1 = // A curve
const curve2 = // A curve
const curve3 = // A curve
const curve4 = // A curve
geometry.rotateX( Math.PI );const numberOfInstances = 8;
const numberOfCurves = 4;
const flow = new InstancedFlow( numberOfInstances, numberOfCurves, geometry, material );// Add the flow object to the scene
scene.add( flow.object3D );
flow.updateCurve( 0, curve1 );
flow.updateCurve( 1, curve2 );
flow.updateCurve( 2, curve3 );
flow.updateCurve( 3, curve4 );
// Do each step below for each numberOfInstances// Set the first instance to be on the first curve
flow.setCurve( 0, 0 );
// Move the first instance along the curve by a random amount
flow.moveIndividualAlongCurve( 0, Math.random() );
// Give the first instance a random Color
flow.object3D.setColorAt( 0, new THREE.Color( 0xffffff * Math.random() ) );