Okay, this is a fun one! We'll create a p5.js sketch with 30 colorful boids employing classic flocking behaviors (separation, alignment, cohesion) and constrain them to swim inside a rotating hexagon. The "supernova nebulae" aesthetic will guide our color choices and background.
Here's the code. You can paste this directly into a p5.js editor (like the one at editor.p5js.org).
javascript
// p5.js Swarm of Boids in Rotating Hexagon (Nebula Theme)
// Global variables for hexagon
let hexRadius;
let hexAngle = 0;
let hexRotationSpeed = 0.005; // Radians per frame
let staticHexVertices = []; // To store the unrotated vertices for point-in-polygon test
let boids = [];
const NUM_BOIDS = 30;
// Flocking parameters
let perceptionRadius = 50; // How far a boid can "see" others for alignment/cohesion
let separationDistance = 25; // Desired minimum distance between boids
function setup() {
createCanvas(windowWidth, windowHeight);
colorMode(HSB, 360, 100, 100, 100); // Hue, Saturation, Brightness, Alpha
angleMode(RADIANS); // Use radians for rotation
// Calculate hexagon size based on canvas dimensions
hexRadius = min(width, height) * 0.4;
// Calculate static (unrotated) hexagon vertices, centered at (0,0)
// These are used for the point-in-polygon check
for (let i = 0; i < 6; i++) {
// PI/6 offset makes the hexagon have a flat top/bottom
let angle = (PI / 3) * i - PI / 6;
staticHexVertices.push(createVector(hexRadius * cos(angle), hexRadius * sin(angle)));
}
// Initialize boids
for (let i = 0; i < NUM_BOIDS; i++) {
// Start boids near the center to ensure they are initially inside the hexagon
let startX = width / 2 + random(-hexRadius * 0.5, hexRadius * 0.5);
let startY = height / 2 + random(-hexRadius * 0.5, hexRadius * 0.5);
boids.push(new Boid(startX, startY));
}
}
function draw() {
// Nebula-like background: dark, slightly transparent for trails
background(240, 60, 10, 85); // Dark blue/purple (Hue 240, Sat 60, Brightness 10, Alpha 85)
// Update and draw the rotating hexagon
hexAngle += hexRotationSpeed;
drawHexagon();
// Update and display boids
for (let boid of boids) {
boid.flock(boids); // Calculate flocking forces
boid.update(); // Apply forces, update position/velocity
boid.boundaries(); // Apply boundary constraints (stay inside hexagon)
boid.display(); // Draw the boid
}
}
function drawHexagon() {
push();
translate(width / 2, height / 2); // Move to canvas center
rotate(hexAngle); // Rotate the coordinate system
noFill();
stroke(0, 0, 100, 70); // Whiteish stroke, somewhat transparent
strokeWeight(3);
beginShape();
for (let v of staticHexVertices) { // Use pre-calculated static vertices
vertex(v.x, v.y);
}
endShape(CLOSE);
pop();
}
// Point-in-polygon test (ray-casting algorithm)
// Checks if a point `p` is inside a polygon defined by vertices `vs`
function pointInPolygon(p, vs) {
let x = p.x, y = p.y;
let inside = false;
for (let i = 0, j = vs.length - 1; i < vs.length; j = i++) {
let xi = vs[i].x, yi = vs[i].y;
let xj = vs[j].x, yj = vs[j].y;
let intersect = ((yi > y) != (yj > y)) &&
(x < (xj - xi) * (y - yi) / (yj - yi) + xi);
if (intersect) inside = !inside;
}
return inside;
}
class Boid {
constructor(x, y) {
this.position = createVector(x, y);
this.velocity = p5.Vector.random2D(); // Random initial direction
this.velocity.setMag(random(2, 4)); // Random initial speed
this.acceleration = createVector();
this.maxForce = 0.2; // Maximum steering force
this.maxSpeed = 4; // Maximum speed
this.r = 4; // Boid size (radius for drawing triangle)
// Nebula-like colors: blues, purples, pinks, cyans
let hue = random(180, 300); // Range: Cyan -> Blue -> Magenta
this.color = color(hue, random(70, 90), random(80, 100), 90); // Main color
this.glowColor = color(hue, random(60, 80), 100, 25); // Softer glow color
}
applyForce(force) {
this.acceleration.add(force);
}
// We accumulate a new acceleration each frame based on three rules
flock(allBoids) {
let sep = this.separate(allBoids); // Separation
let ali = this.align(allBoids); // Alignment
let coh = this.cohesion(allBoids); // Cohesion
// Arbitrarily weight these forces
sep.mult(2.5); // Separation is often weighted more heavily
ali.mult(1.0);
coh.mult(1.0);
// Add the force vectors to acceleration
this.applyForce(sep);
this.applyForce(ali);
this.applyForce(coh);
}
// Method to update location
update() {
// Update velocity
this.velocity.add(this.acceleration);
// Limit speed
this.velocity.limit(this.maxSpeed);
this.position.add(this.velocity);
// Reset acceleration to 0 each cycle
this.acceleration.mult(0);
}
// A method that calculates and applies a steering force towards a target
// STEER = DESIRED MINUS VELOCITY
seek(target) {
let desired = p5.Vector.sub(target, this.position); // A vector pointing from the location to the target
// Normalize desired and scale to maximum speed
desired.setMag(this.maxSpeed);
// Steering = Desired minus Velocity
let steer = p5.Vector.sub(desired, this.velocity);
steer.limit(this.maxForce); // Limit to maximum steering force
return steer;
}
// Separation: Check for nearby boids and steer away
separate(allBoids) {
let steer = createVector(0, 0);
let count = 0;
// For every boid in the system, check if it's too close
for (let other of allBoids) {
let d = dist(this.position.x, this.position.y, other.position.x, other.position.y);
// If the distance is greater than 0 and less than an arbitrary amount (0 when you are yourself)
if ((d > 0) && (d < separationDistance)) {
// Calculate vector pointing away from neighbor
let diff = p5.Vector.sub(this.position, other.position);
diff.normalize();
diff.div(d); // Weight by distance (the closer, the stronger the repulsion)
steer.add(diff);
count++; // Keep track of how many
}
}
// Average -- divide by how many
if (count > 0) {
steer.div(count);
}
// As long as the vector is greater than 0
if (steer.magSq() > 0) { // Use magSq for efficiency
// Implement Reynolds: Steering = Desired - Velocity
steer.setMag(this.maxSpeed);
steer.sub(this.velocity);
steer.limit(this.maxForce);
}
return steer;
}
// Alignment: Forall nearby boids in perception radius, calculate average velocity
align(allBoids) {
let sum = createVector(0, 0);
let count = 0;
for (let other of allBoids) {
let d = dist(this.position.x, this.position.y, other.position.x, other.position.y);
if ((d > 0) && (d < perceptionRadius)) {
sum.add(other.velocity);
count++;
}
}
if (count > 0) {
sum.div(count);
sum.setMag(this.maxSpeed); // Steer towards average direction at maxSpeed
let steer = p5.Vector.sub(sum, this.velocity);
steer.limit(this.maxForce);
return steer;
} else {
return createVector(0, 0);
}
}
// Cohesion: Forall nearby boids, calculate average location
cohesion(allBoids) {
let sum = createVector(0, 0);
let count = 0;
for (let other of allBoids) {
let d = dist(this.position.x, this.position.y, other.position.x, other.position.y);
if ((d > 0) && (d < perceptionRadius)) {
sum.add(other.position); // Add location
count++;
}
}
if (count > 0) {
sum.div(count);
return this.seek(sum); // Steer towards the average location
} else {
return createVector(0, 0);
}
}
// Keep boids inside the rotating hexagon
boundaries() {
let hexCenter = createVector(width / 2, height / 2);
// Transform boid's current world position to the hexagon's local coordinate system
// 1. Translate boid position so hexagon center is origin
let localBoidPos = p5.Vector.sub(this.position, hexCenter);
// 2. Rotate boid position by the *negative* of the hexagon's current angle
localBoidPos.rotate(-hexAngle); // Key step!
// Check if this localBoidPos is inside the static (unrotated) hexagon
if (!pointInPolygon(localBoidPos, staticHexVertices)) {
// If outside, create a strong steering force towards the hexagon's world center
let desired = p5.Vector.sub(hexCenter, this.position);
desired.setMag(this.maxSpeed);
let steer = p5.Vector.sub(desired, this.velocity);
steer.limit(this.maxForce * 3); // Stronger boundary force
this.applyForce(steer);
}
// Additional failsafe: if a boid gets *very* far out (e.g. > hexRadius), pull it back
// This can sometimes happen if boundary forces aren't tuned perfectly or maxSpeed is very high
let dToCenter = dist(this.position.x, this.position.y, hexCenter.x, hexCenter.y);
if (dToCenter > hexRadius * 1.1) { // If it's noticeably outside the main radius
let pullToCenter = this.seek(hexCenter);
pullToCenter.mult(0.5); // A moderate pull
this.applyForce(pullToCenter);
}
}
// Draw boid as a triangle rotated in the direction of velocity
display() {
let theta = this.velocity.heading() + PI / 2; // Angle for rotation
push();
translate(this.position.x, this.position.y);
rotate(theta);
// Glow effect
fill(this.glowColor);
noStroke();
ellipse(0, 0, this.r * 3.5, this.r * 3.5); // Larger, more transparent ellipse for glow
// Boid body (triangle)
fill(this.color);
// noStroke(); // Or a very faint stroke if desired
beginShape();
vertex(0, -this.r * 2); // Top point
vertex(-this.r, this.r * 2); // Bottom-left point
vertex(this.r, this.r * 2); // Bottom-right point
endShape(CLOSE);
pop();
}
}
// Handle window resize
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
// Recalculate hexagon properties based on new canvas size
hexRadius = min(width, height) * 0.4;
staticHexVertices = []; // Clear old vertices
for (let i = 0; i < 6; i++) {
let angle = (PI / 3) * i - PI / 6;
staticHexVertices.push(createVector(hexRadius * cos(angle), hexRadius * sin(angle)));
}
// Note: Boids might briefly be outside the new hexagon after resize.
// The boundary conditions will pull them back in.
// For a smoother resize, one might re-check and reposition boids,
// but this simpler approach is often sufficient.
}
Key Features and Explanation:
Nebula Aesthetics:
colorMode(HSB, ...): Hue, Saturation, Brightness mode makes it easier to get vibrant, related colors.
background(240, 60, 10, 85): A dark, desaturated blue/purple (Hue 240 is blue). The alpha value (85 out of 100) creates faint trails as boids move, enhancing the nebula feel.
Boid.color: Boids get random hues in the cyan-blue-magenta range (random(180, 300)), with high saturation and brightness.
Boid.glowColor: A secondary, more transparent color for a soft glow around each boid.
drawHexagon(): The hexagon has a whitish, semi-transparent stroke.
Rotating Hexagon:
hexAngle is incremented each frame by hexRotationSpeed.
In drawHexagon(), translate() moves the origin to the canvas center, rotate(hexAngle) rotates the coordinate system, and then the hexagon is drawn around this new (0,0).
staticHexVertices: The hexagon's vertex coordinates (relative to its center) are calculated once in setup(). This is important for the boundary check.
flock(boids): Orchestrates the three flocking rules:
separate(boids): Steers to avoid crowding local flockmates.
align(boids): Steers towards the average heading of local flockmates.
cohesion(boids): Steers to move toward the average position of local flockmates.
update(): Applies acceleration to velocity, velocity to position, and limits speed.
seek(target): A common steering behavior to move towards a target.
display(): Draws the boid as a triangle pointing in its direction of travel, with a glow effect.
boundaries(): This is crucial.
This setup provides a dynamic and visually appealing simulation. The boids should exhibit emergent flocking behavior while being contained within the mesmerizingly rotating hexagon, all set against a cosmic backdrop.
It translates this position so that the hexagon's center becomes the origin.
It then rotates this translated position by the negative of the hexagon's current angle. This effectively gives the boid's position as if the hexagon were static and unrotated.
It uses the pointInPolygon() function with the staticHexVertices (which are unrotated) to check if the boid is inside.
If outside, a strong force steers the boid back towards the hexagon's world center.
A failsafe pull is added if the boid gets very far out.
pointInPolygon(point, vertices) function:
A standard ray-casting algorithm. It determines if a point is inside a polygon by counting how many times a ray extending from the point intersects the polygon's edges. An odd number of intersections means the point is inside.
windowResized():
Ensures the sketch adapts if the browser window size changes. It recalculates the hexagon's dimensions.