Introduction
Inspired by my last flocking project, I want to transplant it into three.js. Therefore, I did a few experiments and figured out how to make fish flocks with three.js with this reference.
Step 1: Setting up the Scene and Renderer
The first step in creating any Three.js scene is to set up the scene, the camera, and the renderer. I set up the scene, a Camera, and a WebGLRenderer to create the environment.
Step 2: Adding the Box Container
Creating the Box
The BoxContainer represents the environment’s boundary. I used a BoxGeometry to create the box shape and a MeshLambertMaterial for the material. The box serves as a boundary for the scene, although it is invisible because it’s wireframe.
Step 3: Adding the Bellwether
Shape and Movement
The Bellwether is a moving object created using a CylinderGeometry. The object moves randomly by applying small changes in its velocity and acceleration using vectors:
const geometry = new THREE.CylinderGeometry(1, 30, 50, 12);
const material = new THREE.MeshLambertMaterial({ color: 0xff0000 });
const bellwether = new THREE.Mesh(geometry, material);
scene.add(bellwether);
this.velocity.add(this.acceleration);
this.mesh.position.add(this.velocity);
Step 5: Adding the Chasers
Chaser Shape and Behavior
The Chasers are created using smaller CylinderGeometry objects. Each Chaser attempts to follow the Bellwether, and the chasers are designed to avoid each other to simulate flocking behavior.
Chaser Movement
Each Chaser uses the same “seek” behavior. Additionally, the chasers use a “separate” behavior to avoid getting too close to each other.
