Sure! Below is a p5.js sketch that creates a smooth, circle-based fish that follows the mouse pointer. The fish is composed of multiple interconnected circles with parent-child relationships, ensuring smooth movement and avoiding intersection. The outline is rendered smoothly using a convex hull algorithm with a shrink parameter to control the tightness of the fit.
Overview
- Fish Structure: The fish is built using a hierarchical structure of circles (
FishCircle class). Each circle has a parent (except the root/nose) and maintains an offset relative to its parent.
- Movement: Each circle moves toward its target position based on its parent's position, with elasticity and friction applied to create smooth motion.
- Collision Avoidance: By maintaining proper offsets and updating positions based on parents, circles naturally avoid overlapping.
- Rendering: To create a smooth outline, the sketch computes a convex hull around all the circles and renders it using
beginShape() with curveVertex() for smooth bezier curves.
Implementation
Here's the complete p5.js code. You can run this code in the p5.js online editor or your local environment.
let fish;
let elasticity = 0.1; // Controls how strongly circles follow their target positions
let friction = 0.9; // Controls the damping of velocities
let shrink = 0.5; // Controls the tightness of the outline (0 to 1)
function setup() {
createCanvas(800, 600);
// Initialize the fish at the center
fish = new Fish(createVector(width / 2, height / 2));
}
function draw() {
background(220);
// Update and display the fish
fish.update();
fish.display();
}
// ---------------- Fish Classes ---------------- //
class Fish {
constructor(position) {
// Initialize the fish with its hierarchical circles
this.root = new FishCircle(position, 20, null, createVector(0, 0));
// Midsection
this.midsection = new FishCircle(
p5.Vector.add(this.root.pos, createVector(30, 0)),
40,
this.root,
createVector(30, 0)
);
this.root.addChild(this.midsection);
// Fins
this.leftFin = new FishCircle(
p5.Vector.add(this.midsection.pos, createVector(-20, -30)),
15,
this.midsection,
createVector(-20, -30)
);
this.rightFin = new FishCircle(
p5.Vector.add(this.midsection.pos, createVector(-20, 30)),
15,
this.midsection,
createVector(-20, 30)
);
this.midsection.addChild(this.leftFin);
this.midsection.addChild(this.rightFin);
// Tail base
this.tailBase = new FishCircle(
p5.Vector.add(this.midsection.pos, createVector(60, 0)),
15,
this.midsection,
createVector(60, 0)
);
this.midsection.addChild(this.tailBase);
// Tail fins
this.leftTailFin = new FishCircle(
p5.Vector.add(this.tailBase.pos, createVector(20, -20)),
20,
this.tailBase,
createVector(20, -20)
);
this.rightTailFin = new FishCircle(
p5.Vector.add(this.tailBase.pos, createVector(20, 20)),
20,
this.tailBase,
createVector(20, 20)
);
this.tailBase.addChild(this.leftTailFin);
this.tailBase.addChild(this.rightTailFin);
// Collect all circles for easy access
this.circles = [
this.root,
this.midsection,
this.leftFin,
this.rightFin,
this.tailBase,
this.leftTailFin,
this.rightTailFin,
];
// Attach all circles to a hierarchy
// The root's target is the mouse position
this.target = createVector(mouseX, mouseY);
}
update() {
// Update the target to the mouse position
this.root.target = createVector(mouseX, mouseY);
// Update all circles
for (let circle of this.circles) {
circle.update();
}
}
display() {
// Draw circles for debugging (optional)
/*
for (let circle of this.circles) {
noFill();
stroke(0);
ellipse(circle.pos.x, circle.pos.y, circle.radius * 2);
}
*/
// Compute the outline
let outlinePoints = [];
// For each circle, get points around its perimeter
let resolution = 16; // Number of points per circle
for (let circle of this.circles) {
for (let i = 0; i < resolution; i++) {
let angle = map(i, 0, resolution, 0, TWO_PI);
let x = circle.pos.x + cos(angle) * circle.radius;
let y = circle.pos.y + sin(angle) * circle.radius;
outlinePoints.push(createVector(x, y));
}
}
// Compute the convex hull
let hull = convexHull(outlinePoints);
// Optionally apply shrink parameter
if (shrink > 0) {
hull = shrinkHull(hull, shrink);
}
// Draw the fish body
noStroke();
fill(100, 150, 240); // Fish color
beginShape();
for (let v of hull) {
curveVertex(v.x, v.y);
}
// To make the curve loop smoothly
for (let i = 0; i < 2; i++) {
let index = i % hull.length;
curveVertex(hull[index].x, hull[index].y);
}
endShape(CLOSE);
}
}
class FishCircle {
constructor(position, radius, parent, offset) {
this.pos = position.copy(); // Current position
this.vel = createVector(0, 0); // Current velocity
this.radius = radius; // Radius of the circle
this.parent = parent; // Parent FishCircle
this.offset = offset.copy(); // Desired offset from the parent
this.children = []; // Array of child FishCircles
this.target = null; // Target position (only for root)
}
addChild(child) {
this.children.push(child);
}
update() {
if (this.parent) {
// Desired position based on parent's position and offset
let desiredPos = p5.Vector.add(this.parent.pos, this.offset);
// Vector towards desired position
let dir = p5.Vector.sub(desiredPos, this.pos);
dir.mult(elasticity);
// Update velocity
this.vel.add(dir);
// Prevent overlap with parent
let minDist = this.parent.radius + this.radius;
let currentDist = p5.Vector.dist(this.pos, this.parent.pos);
if (currentDist < minDist) {
let overlap = minDist - currentDist;
let away = p5.Vector.sub(this.pos, this.parent.pos).normalize();
this.vel.add(away.mult(overlap * elasticity));
}
}
// Apply friction
this.vel.mult(friction);
// Update position
this.pos.add(this.vel);
}
}
// ---------------- Utility Functions ---------------- //
// Compute the convex hull using Graham scan algorithm
// Returns the hull as an array of p5.Vector
function convexHull(points) {
if (points.length < 3) return points;
// Sort points lexicographically
points.sort((a, b) => {
if (a.x === b.x) return a.y - b.y;
return a.x - b.x;
});
let lower = [];
for (let p of points) {
while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) {
lower.pop();
}
lower.push(p);
}
let upper = [];
for (let i = points.length - 1; i >= 0; i--) {
let p = points[i];
while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) {
upper.pop();
}
upper.push(p);
}
// Concatenate lower and upper to get full hull
lower.pop();
upper.pop();
return lower.concat(upper);
}
// Cross product of OA and OB vectors
function cross(o, a, b) {
return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
}
// Optional: Shrink the hull towards its centroid by a factor
function shrinkHull(hull, shrinkFactor) {
// Compute centroid
let centroid = createVector(0, 0);
for (let v of hull) {
centroid.add(v);
}
centroid.div(hull.length);
// Move each point towards the centroid
let shrunk = hull.map(v => {
let dir = p5.Vector.sub(v, centroid);
dir.mult(shrinkFactor);
return p5.Vector.add(centroid, dir);
});
return shrunk;
}
Explanation of Key Components
-
Fish Structure:
- The
Fish class initializes the fish's hierarchical structure starting with the root (nose).
- Each
FishCircle represents a part of the fish (nose, midsection, fins, tail) and maintains an offset relative to its parent.
- The
circles array in the Fish class holds all parts for easy updating and rendering.
-
Movement Mechanics:
- Each
FishCircle updates its position based on its parent's position and a specified elasticity.
friction is applied to the velocity to prevent perpetual motion and ensure smooth settling.
- Collision avoidance is handled by checking the distance between a circle and its parent, adjusting velocity if they're too close.
-
Rendering the Smooth Outline:
- Points are sampled around the perimeter of each circle.
- A convex hull is computed from all these points to form the outer boundary of the fish.
- The
shrink parameter allows adjusting the tightness of the hull around the circles. A shrink of 1 tightly wraps the circles, while 0 minimizes bending.
- The hull is drawn using
beginShape(), curveVertex(), and endShape(CLOSE) to create smooth bezier curves for the outline.
-
Utility Functions:
convexHull: Implements the Graham scan algorithm to compute the convex hull of a set of points.
cross: Helper function for calculating the cross product, used in the convex hull algorithm.
shrinkHull: Optionally shrinks the convex hull towards its centroid based on the shrinkFactor.
Customization
-
Parameters:
elasticity: Adjusts how strongly each circle follows its target. Higher values make the fish more responsive.
friction: Controls the damping of movement. Values closer to 1 retain more velocity, while lower values dampen motion quickly.
shrink: Alters the convex hull tightness. Values range from 0 (loose fit) to 1 (tight fit).
-
Fish Structure:
- You can modify the size, number, and positions of the circles to create different fish shapes.
- Adding more child circles or adjusting offsets can introduce additional features like more fins or different tail shapes.
Running the Sketch
To see the fish in action, copy the above code into the p5.js online editor and click the play button. Move your mouse around the canvas, and the fish will follow the pointer smoothly, maintaining its shape and avoiding intersections between its parts.
Feel free to tweak the parameters (elasticity, friction, shrink) and the fish's structure to achieve different behaviors and appearances!