My main inspiration came from my dear friend Youssab William’s midterm project ASCENT. I love the idea of platformers and honestly Youssab inspired me to make something on p5 that has platformer mechanics.
As an act of creative freedom and my usual obsession with ownership, I want to call this project Giuseppe.
soooo here’s the sketch. Use Arrows or WASD to move
but wait. this isn’t a platformer. not even close actually. so what happened? we will explore that in this documentation
Before writing a single line, I mapped out what matter.js actually needed to do for this to work. I created a simple platformer and saw how things will go from there.
Well…yeah.. this wasnt what I expected. I don’t know what I expected hoenstly. Just not something… this bad?
I immediately scrapped the idea after this video. But before pulling out my hair and making yet another 17th sketch trying to think for a concept for this assignment, I noticed that the little red cube sticks on the sides of the platforms. This sparked an idea in me, a parkour-like game that a ninja (later simplified to a cube) jumping from wall to wall to avoid the lava. Just like those old mobile games. Then Giuseppe was born.
The concept is a vertical survival game. You wall-jump up an endless shaft while lava rises beneath you. There are zones. There are coins. There is a freaking lava floor that will inevitably come and get you.
The player body never has velocity set directly except during wall jumps. Everything else is force application. Horizontal movement applies a constant force every frame:
let moveForce = 0.0012;
if (keyIsDown(LEFT_ARROW) || keyIsDown(65))
Body.applyForce(playerBody, playerBody.position, { x: -moveForce, y: 0 });
if (keyIsDown(RIGHT_ARROW) || keyIsDown(68))
Body.applyForce(playerBody, playerBody.position, { x: moveForce, y: 0 });
if (playerBody.velocity.x > 5)
Body.setVelocity(playerBody, { x: 5, y: playerBody.velocity.y });
if (playerBody.velocity.x < -5)
Body.setVelocity(playerBody, { x: -5, y: playerBody.velocity.y });
The speed cap is load-bearing. Without it the player accelerates forever and becomes impossible to control in about four seconds. The cap is also what makes the movement feel snappy rather than floaty, because the player reaches max speed almost immediately and stays there. Force application without a cap is just a slow velocity set with extra steps
I then entered my usual 3 am flowstate and I reached this position.
[im trying to upload but facing issues so i cant really upload attachments]
Thr wall grip part is the part I’m most proud of, and also the part that took the longest to not be horrible.
The grip has two phases. When the player first touches a wall, the engine fires a counter-force upward that decays linearly to zero over 4000ms. At t=0 the counter-force exactly cancels gravity so the player feels weightless on the wall. By t=4000ms it’s gone and the player slides off. After the grip expires there’s a 500ms push-off phase where a small lateral force nudges the player away from the wall and canjump is set to false, so you can’t wall-jump from a dead grip.
if (contactAge < GRIP_DURATION) {
let t = contactAge / GRIP_DURATION;
let counterForce = lerp(0.0012, 0, t);
Body.applyForce(playerBody, playerBody.position, {
x: 0,
y: -counterForce,
});
} else if (contactAge < GRIP_DURATION + PUSH_DURATION) {
Body.applyForce(playerBody, playerBody.position, {
x: -wallSide * 0.0015,
y: 0,
});
canJump = false;
}
The 0.0012 is not random. matter.js default gravity produces a downward acceleration of 0.001 per update tick at default settings. The counter-force matches it exactly so the player hovers. I lied, AI found that value for me when I asked it why the player was either rocketing upward or sliding instantly. The fix was embarrassingly simple once I knew what to look for.
The grip timer also renders as a visual bar on the wall panel. The bar height shrinks as grip time expires and turns red during the push-off phase so you always know exactly how much time you have left. I added that late and it completely changed how readable the game was.
The collision architecture has three events all running simultaneously.
beforeUpdate resets canJump, wallSide, and touchingWall to false/zero every single frame before any collision detection runs. This is important because matter.js collision events only fire when contact is active, which means if nothing fires this frame, the flags stay false. No ghost jumps. No lingering wall contact.
collisionActive runs every frame the player overlaps any surface and handles all the grip logic above. It’s also where wallSide gets set, by comparing the player’s x position to the wall body’s x position to determine which side the wall is on.
collisionStart handles orb collection as a one-shot event. Orbs are sensor bodies so they have zero physical response, but they still fire collision events. When an orb-player pair is detected, collectOrb() removes the body from the world, increments the coin count, and spawns a particle burst.
Events.on(physEngine, "collisionStart", function (event) {
for (let pair of event.pairs) {
let bodyA = pair.bodyA, bodyB = pair.bodyB;
if (
(bodyA.label === "Orb" || bodyB.label === "Orb") &&
(bodyA.label === "Player" || bodyB.label === "Player")
) {
collectOrb(bodyA.label === "Orb" ? bodyA : bodyB);
}
}
});
The game has five zones that unlock at ascending height thresholds. Each zone changes the wall color, background color, and lava color simultaneously. The transition happens in one line: currentZone = newZoneIdx, and a banner fades in with the zone name then dissipates over about 100 frames.
The zone palette design was fun. I wanted each zone to feel like a different biosphere. SURFACE is warm red on near-black. THE CAVERNS goes amber on deep brown. CRYSTAL DEEP goes cold blue on dark navy. THE STORM goes violet on almost-black. THE VOID goes teal on pure void. The lava color shifts with the zone too, so in CRYSTAL DEEP the rising floor is a cold electric blue rather than orange, which is a detail I’m very happy with and nobody will probably notice.
The first working version was a flat canvas with a rectangle and a ground. No camera, no walls, just a box with gravity and a jump. That worked in maybe 30 minutes. Everything after that was a long series of things that almost worked.
The wall detection broke me for a while. The original approach used collisionActive to detect wall contact but I kept getting canJump = true from the ground at the same time as wallSide = 1 from a wall, which meant ground jumps sometimes registered as wall jumps and gave you the kick-off velocity by accident. The fix was the label check: if (surfaceBody.label !== "Wall" && surfaceBody.label !== "Ground") continue gates everything behind identity. The floor has label “Ground” and never sets wallSide. Walls have label “Wall” and never set canJump during push-off. Clean separation.
The camera also gave me problems. My first implementation was camY = CANVAS_H/2 - playerBody.position.y with no lerp, which meant the camera snapped instantly to the player position and the whole canvas strobed. Adding the lerp (camY = lerp(camY, camYTarget, 0.1)) was one line and made the whole thing feel like a proper game. That 0.1 lerp factor took me a while to find. At 0.05 the camera felt detached. At 0.2 it still twitched. 0.1 was the number.
The game is more playable than I expected at this stage. The wall jump interaction teaches itself within about three or four deaths, which is a good sign. Players understand immediately that the walls are grippable and that the lava is not.
The zone system adds something I wasn’t sure would land. The color transitions give the game a sense of depth even though the gameplay is identical in every zone. There’s something psychologically effective about a wall turning violet that makes you feel like you’ve gone somewhere.
Two things I’m not settled about. The lava speed is constant right now and it should probably accelerate as you get deeper into the game. A flat rise rate means the game’s difficulty is almost entirely dependent on your wall jump skill, which is fine but I think a rising speed floor would create more interesting decision moments. The second thing is audio. The game is very silent and I think a low bass rumble that rises in pitch as the lava approaches would communicate danger in a way the red vignette edge alone doesn’t quite reach. The vignette is good. Sound would make it visceral.
I also want to revisit the particle burst on wall jump. Right now it’s an orange burst at the jump origin, which looks fine. I think making it directional, so the particles kick backward from the wall jump direction, would make the jump feel more physically grounded without any extra complexity.
This project is inspired by murmuration by robert hodgin. It merges algorithmic plant growth with flocking mechanics. The project transitions particles between a structured tree form and a chaotic swarm. I also took inspiration from the reinforcement learning process which is where the idea of generations comes from.
I started by defining the base entity. I created the Boid class then I gave each boid standard steering behaviors. These include separate and align then I added the cohere function. These functions calculate vectors. The boids avoid crowding instead they match velocities with neighbors. Next, I tackled the structural element. I wrote a recursive function named genPts. This function calculates coordinates for a branching fractal tree. The function takes arguments for position and angle then it processes length and depth and it calculates segments using trigonometry. It pushes vectors into a global treePts array but I needed a system to alternate between the two behaviors so I implemented a time-based state machine inside the draw loop. Phase zero represents the growth phase. Boids use an arrive steering behavior to settle into specific coordinates along the fractal branches. Phase one represents the swarm phase. The boids break free. They apply flocking rules.
Particles
flocking
fractar tree generation
putting the particles together
the code i am proud of is regenTree function. It manages the visual evolution of the simulation across generations, then it scales the tree depth. It mutates the branching spread angle and dynamically links the boid objects to the newly generated tree points.
// rebuild tree by age/gen
function regenTree(g) {
treePts = [];
// scale depth/len by gen (cap depth 4 fps)
let maxD = min(3 + floor(g / 2), 6);
let baseLen = min(height * 0.12 + g * 12, height * 0.3);
// mut spread by gen
let spread = PI / (5 + sin(g) * 1.5);
genPts(width / 2, height - 30, -PI / 2, baseLen, maxD, spread);
// sync boids to new pts
for (let i = 0; i < treePts.length; i++) {
if (i < boids.length) {
boids[i].treePos = treePts[i].copy(); // assign new tgt
} else {
// spawn new boids at base to sim growth
boids.push(new Boid(width / 2, height, treePts[i]));
}
}
// trim excess (edge case)
if (boids.length > treePts.length) {
boids.splice(treePts.length);
}
}
A specific challenge involved the arrive steering behavior. The boids would overshoot their target coordinates at high velocities. They would oscillate rapidly around the target point. I adjusted the distance threshold mapping by mapping the boid’s speed to decrease linearly when it enters a 100-pixel radius of its assigned treePos. This adjustment solved the jittering issue.
I plan to add interactive elements. Users will click to disrupt the swarm. I want to introduce a wind force variable. This force will push the boids horizontally. I will implement a visual trail system for the boids to emphasize their flight paths.
There’s something genuinely strange about watching a crowd of autonomous agents share a canvas.
That’s the question behind DRIFT: what happens when you put three radically different vehicle archetypes into the same space, give each one its own agenda, and just let physics run?
The starting point was Craig Reynolds’ foundational work on steering behaviors: seek, flee, separation, alignment, cohesion. Those behaviors are well-documented and well-taught. The challenge I set for myself was to use them as raw material for something that reads more like an ecosystem than a demo.
I ended up with three vehicle types:
Seekers chase a moving attractor that is basically a signal that traces a path across the canvas. They leave luminous trails and pulse as they move.
Drifters ignore the signal entirely. They flock through alignment, cohesion, and separation. and wander using noise.
Ghosts flee. They push away from the signal and from the combined mass of every other vehicle in the scene. They end up haunting the edges of the canvas.
The signal itself moves on a parametric Lissajous curve, so it sweeps the canvas continuously without any user input required.
The Ghost’s `applyBehaviors` method is the piece I find most satisfying. The rule sounds simple — flee everything — but the implementation has a specific texture to it.
javascript
applyBehaviors(signal, allVehicles) {
let fleeSignal = this.flee(signal, 220);
let fleeCrowd = createVector(0, 0);
for (let v of allVehicles) {
fleeCrowd.add(this.flee(v.pos, 90));
}
let w = this.wander(1.2);
fleeSignal.mult(2.0);
fleeCrowd.mult(0.8);
w.mult(0.9);
this.applyForce(fleeSignal);
this.applyForce(fleeCrowd);
this.applyForce(w);
}
What I like here is that `fleeCrowd` is an accumulated vector. For every seeker and drifter on the canvas, the ghost computes a flee force and adds them all together. The result is that the ghost reads the density of the crowd. A ghost near a tight cluster of drifters gets a much stronger push than one near a single seeker. It behaves like a pressure system.
The wander force on top of that means no two ghosts trace the same path even under identical starting conditions. The noise field shifts slowly over time, so the wandering feels natural.
The wander method from the base `Vehicle` class handles this:
Getting the ghost behavior to feel ghostly rather than glitchy. The first version had ghosts with a flee radius too small, so they’d enter the crowd and then snap violently outward. Increasing the signal flee radius to 220 pixels and smoothing the crowd flee with accumulated vectors fixed the snapping.
The Lissajous signal path. My first instinct was to use `mouseX` and `mouseY` as the attractor, which is the standard approach for seek demos. The problem is that a static mouse produces boring convergence, everyone piles up on the target and sits there. A Lissajous curve gave the signal genuine sweep across the canvas, which keeps seekers in motion even after they’ve converged. The math is minimal:
function getSignalPos(t) {
let cx = width * 0.5;
let cy = height * 0.5;
let rx = width * 0.32;
let ry = height * 0.28;
return createVector(
cx + rx * sin(t * 0.41 + 0.6),
cy + ry * sin(t * 0.27)
);
The frequency ratio `0.41 / 0.27` is irrational enough that the path never perfectly repeats, so the sketch keeps shifting over long observation periods.
The three archetypes don’t interact across types in any interesting way. Seekers don’t react to drifters. Drifters don’t notice ghosts. The only cross-archetype behavior is the ghost’s crowd flee, which reads seeker and drifter positions as obstacles. A next version could introduce:
– Seekers that are temporarily distracted by passing drifter clusters, pulled off their trajectory before resuming the chase.
– The signal occasionally splitting into two attractors, creating competing factions among the seekers.
Visually, the grid underneath the simulation was meant to read as a city viewed from above, but it’s almost invisible after the first frame. Rendering it to a persistent background layer would strengthen that spatial metaphor.
This sketch is laggy on p5 web editor so I included a video on VS Code.
This sketch is inspired by teamLab Phenomena’s Light Vortex.
This sketch creates a generative laser show where beams of light emerge from the screen edges and converge to form shifting geometric patterns. The visual experience centers on the idea of a “central attractor” shape. Every beam starts at a fixed position on the edge of the canvas. The end of each beam connects to a point on a central shape. These shapes cycle through circles, squares, triangles, spirals, waves, and stars. As the user triggers a transition using the button Space, the endpoints of the beams slide smoothly from one shape’s perimeter to the next.
I began with a prototype and then improved my sketch.
The logic requires several fixed values to maintain performance and visual density. I chose 144 beams total. This provides 36 beams per side of the screen.
The state variables manage the current shape and the animation progress. transitionT tracks the normalized time (0 to 1) of the current morph.
Each laser is an instance of a Beam class. This class stores the origin point on the screen edge and handles the color logic. The recalcOrigin method assigns each beam to one of the four sides of the rectangle.
recalcOrigin() {
const e = this.edge;
const k = this.index % BEAMS_PER_EDGE;
if (e === 0) { this.ox = W * (k + 0.5) / BEAMS_PER_EDGE; this.oy = 0; }
else if (e === 1) { this.ox = W; this.oy = H * (k + 0.5) / BEAMS_PER_EDGE; }
// ... logic for other two edges
}
To create a “glow” effect, I draw the same line three times with different weights and transparencies. The bottom layer is wide and faint. The top layer is thin and bright white. Basically drawing from the gradiant concept professor Jack showed us when he created a gradient on a circle.
The most technical part of the code involves the getShapePoint function. Every shape needs to map a value t (from 0 to 1) to a coordinate (x, y).
The circle uses basic trigonometry. The square divides $t$ into four segments.
function squarePoint(t, r) {
const seg = t * 4;
const side = Math.floor(seg) % 4;
const frac = seg - Math.floor(seg);
switch (side) {
case 0: return { x: -r + frac * 2 * r, y: -r };
}
}
For polygons, the code treats each side as a separate linear path. For the square, the path is divided into four equal segments. If normT is between 0 and 0.25, the point is on the top edge. If it is between 0.25 and 0.50, it moves to the right edge.
function calcSquareVert(normT, maxRadius) {
const totalSegs = normT * 4;
const activeEdge = Math.floor(totalSegs) % 4;
const edgeLerpFrac = totalSegs - Math.floor(totalSegs);
// map sub-coords based on current active edge
}
When a transition occurs, the code calculates the point for the current shape and the point for the next shape. I use a linear interpolation (lerp) between these two positions. I then apply an easeOutCubic function to make the movement feel more organic and less mechanical. The visual depth increases significantly because of the intersection points. When two beams cross, the code renders a glowing “node.”
I used a standard line-line intersection algorithm. This calculates the exact x and y where two segments meet.
x = x1 + t(x2-x1) and the same for y coordinates.
Drawing every single intersection would ruin the frame rate. I implemented two filters. First, the code only draws a maximum of 800 intersections per frame. Second, I created an intersectionAlpha function. This function checks how close an intersection is to the central shape. Nodes far away from the core are transparent. Nodes near the core glow brightly.
function intersectionAlpha(ix, iy) {
const threshold = min(W, H) * 0.12;
let minD = Infinity;
for (let k = 0; k < SHAPE_SAMPLE_N; k++) {
const d = Math.sqrt((ix - shapeSamples[k].x) ** 2 + (iy - shapeSamples[k].y) ** 2);
if (d < minD) minD = d;
}
return constrain(Math.exp(-3.5 * minD / threshold), 0.03, 1.0);
}
The atmosphere relies on blendMode(ADD). This mode makes colors brighten as they overlap.
Here’s a video of how it looked like before the light leaks. It was so flat so the light leaks were defintely a good addition.
I added a drawLightLeaks function. It uses p5’s noise() to move large, soft radial gradients around the background. These gradients use a low opacity to simulate lens flare or atmospheric haze.
As always with all of my sketches, I faced a performance issue. Thankfully after running into preformance issues a billion times in my life I managed to get better with knowing how to resolve them. Calculating 144 origins and 150 shape samples every frame is cheap. Calculating thousands of potential intersections is expensive. Drawing every intersection would create too much visual noise. The calcIntersectAlpha function calculates the distance between an intersection point and the nearest point on the central shape. Nodes far away from the core are transparent. Nodes near the core glow brightly.
updateCachedEnds: This function runs once at the start of the draw() loop. It stores the end position of every beam. This prevents the intersection loop from recalculating the morphing math thousands of times.
updateShapeCache: This pre-calculates the geometry of the central shape. The intersection alpha function uses this cache to quickly check distances without running the shape math again.
Collision Cap: I set MAX_LINE_INTERSECTS to 800. This ensures the computer never tries to render too many glowing dots at once.
For future improvements, I tried making the light beams draw an illusion of a 3d shape while still in a 2d canvas. This kind of worked but kind of didn’t because I think I would need to implement dynamic scaling because the canvas looked overwhelming even thou you can still see the object. I decided to scrap this idea and remove it from the code. here’s how it looked like.
As crazy as it sounds, a big inspiration of this sketch is a song by a not very well known band called fairtrade narcotics. Especially the part that starts around 4:10 , as well this video: Instagram
To toggle modes, press space to change to Galaxy and press Enter to change to Membrane
GALACTIC is an interactive particle system built around a single mechanic: pressure. Pressure from the mouse, pressure of formation, and pressure of, holding it together. This sketch is built around the state of mind I had when I first discovered the song in 2022. I played it on repeat during very dark times and it was mending my soul. After every successful moment I had at that time, during my college application period, I would play that specific part of the song and it would lift me to galactic levels. The sketch has 3 modes, the charging modes resembles when I put in a lot of effort into something and eventually it works out which is resembled by the explosion. The second state is illustrates discipline by forming the particles into a galaxy. The last is Membrane which represents warmth and support from all my loved ones.
Before writing a single line, I sketched the architecture on paper. The system has three major layers of responsibility: the global state (are we holding? are we exploding? what’s the charge level?), the particle population (a pool of objects that each manage their own physics), and the vfx (trails, embers, glow pulses, which are short-lived visual elements that don’t need the full particle class). I accumulated my notes and compiled them into a beautiful psuedocode that I can follow, this is me abusing what I learned taking Data Structures and honestly desgining the system beforehand works for me really well
please check the pdf for the psuedcode because there’s this ANNOYING issue that no matter whats the scale of the screenshot I am uploading its always so blurry and small.
I also want to disclose that AI helped me with many mathematical sections within this sketch, I wouldn’t be able to understand the math or get around it on my own I think. But I promise my usage is not excessive or dependent and I actually use it to learn haha
Anyway, I started writing attributes for the particle class and oh boy they added up QUICKLY. Here’s a snippet. I tried assigning random values manually but it was very very hard to find the sweet spot for everything so I used some help from AI to assign the proper values to those attributes and I tweaked them a little bit and got really good results.
A useful frame for interactive generative art is the state machine. This sketch has three primary states that produce visually distinct experiences, and the transitions between them are where most of the design work happened.
Idle state: No mouse interaction. 80 particles drift across the canvas on Perlin noise. Each particle has its own noise offset, frequency, and speed. The result is slow, organic, slightly hypnotic. The palette sits in the 228-288 HSB hue range (blue through violet) and particles breathe gently at a rate of 2 cycles per second. This is the sketch’s resting face, and it needs to be beautiful enough to watch on its own.
Charging state: Mouse held. New particles spawn at the edge of the screen and get pulled toward the cursor which acts as an attractor. Spawn rate accelerates from 1/frame to 18/frame as charge approaches maximum. The vortex arms appear past 8% charge: three logarithmic spirals that rotate faster as charge builds, drawn with beginShape()/vertex() and per-vertex stroke colors that fade toward the outer edge. The glow orb grows around the cursor. Screen rumble starts at 60% charge. Particles near the cursor compress and brighten. The hue of nearby particles shifts toward 305, a hot magenta-violet. Every visual element does the same narrative work: energy is accumulating.
Explosion state: Mouse released. This is tiered across four discrete levels (0 through 3) based on charge thresholds at 0.25, 0.55, and 0.85. Tier 0 is a gentle push. Tier 3 is a white-flash, screen-shake, 800-pixel-radius detonation that spawns up to 70 child particles from split candidates nearest the blast origin. Each particle in blast range gets a force vector calculated from distance falloff (pow(1 - d/blastRadius, 2)), a random rotation drift, and a behavior assignment weighted by proximity to center and charge level. The explosion duration scales with charge, from 1.4 seconds to 4 seconds. The slowdown at high charge gives full-tier explosions a cinematic quality: the cloud expands, holds, then dissipates.
The variation space this produces is wide. A quick series of light taps creates a dotted constellation. Holding in one place while moving slightly creates smeared, comet-like trails. A patient full charge, held long enough to feel the rumble, produces a different kind of satisfaction.
the scariest things about this project were two things braided together: performance under additive blending with 700+ particles, and making the multi-behavior explosion feel coherent rather than random.
Additive blending (blendMode(ADD)) is visually spectacular. Overlapping particles bloom into white rather than muddy brown. The cost is real though: each ellipse composites against everything underneath it. With three ellipses per particle (the outer glow halo, the mid-glow body, and the bright core), plus trail objects, plus embers, a naive implementation at 700 particles hits framerate problems fast. The risk was a beautiful system running at 20fps. I ran many optimization processes but then I migrated to VS code which was MUCH smoother but I don’t know how smart that is going to be because in the end I’m gonna have to embed the sketch in p5.js web editor so it wouldn’t make sense or a difference that it runs smoothy on my device but its laggy on the website.
For the behavior system, the risk was that five different particle behaviors during explosion would read as a mess of conflicting physics. To test this, I implemented behaviors one at a time and ran the explosion at full charge with only that behavior active, watching whether each produced a readable visual signature. BEHAVE_COMET needed the highest speed and the lowest drag (0.99 vs the standard 0.93-0.97) to produce visible streaks. BEHAVE_BOOMERANG needed the timer offset: if the return force kicked in immediately, particles just wobbled. They needed to actually leave the origin first. BEHAVE_FLUTTER was the most unpredictable and required the dampening multiplier (vx *= 0.985) to prevent runaway acceleration from the oscillating force.
The assignBehavior() method’s probability table weights behavior by charge level and proximity to blast center. Close-in particles at high charge get COMET and SPIRAL; far particles get RADIAL and FLUTTER. This creates a natural visual structure: a dense bright core of fast-moving comets surrounded by a slowly oscillating outer cloud. The explosion has a center and a periphery, which reads as physically plausible even though the physics are entirely invented.
But there comes another problem. I don’t like the black background so I decided to create a galaxy background. I had a rough idea how to make it but I had to do some research.
Guess what, all of those links were useless. I found nothing of help but I didn’t want to give up. so I found this reddit post and I found this page and I follwed the principles and methods in the article to create something cool.
I tried to upload the gif of the animated image but I got this error so I will just upload a screenshot unfortunately.
This is a wall a ran into. No matter what I did with the background, it either looked ugly or became very laggy. So I went with the vibe that space by nature is void and light in it is absent, black is the absence of light. Therefore, the background is black. I feel like a good skill of being an artist is to convince people that your approach makes sense when you’re forced to stick with it.
Then I moved to implementing the galaxy.
The galaxy implementation started with a question I couldn’t immediately answer: how do you turn drifting particles into something that looks like a spiral galaxy without teleporting them there? My first instinct was to assign each particle a slot on a pre-calculated spiral arm and pull it toward that slot. I wrote assignGalaxyTargets(), sorted particles by their angle from center, matched them to sorted target positions, and felt pretty good about it.
function assignGalaxyTargets() {
let n = particles.length;
// build target list at fc = 0 (static, for assignment geometry only)
let targets = [];
for (let j = 0; j < n; j++) {
let gi = j * (GALAXY_TOTAL / n);
let pos = galaxyOuterPos(gi, 0);
targets.push({ gi, x: pos.x, y: pos.y,
ang: atan2(pos.y - galaxyCY, pos.x - galaxyCX) });
}
// sort particles by current angle from galaxy center
let sortedP = particles
.map(p => ({ p, ang: atan2(p.y - galaxyCY, p.x - galaxyCX) }))
.sort((a, b) => a.ang - b.ang);
// sort targets by their angle
targets.sort((a, b) => a.ang - b.ang);
// assign in matched order → minimal travel distance
for (let j = 0; j < n; j++) {
sortedP[j].p.galaxyI = targets[j].gi;
}
galaxyAssigned = true;
}
I lied. It looked awful. Particles on the right side of the canvas were getting assigned to slots on the left and crossing the entire screen to get there. The transition looked like someone had scrambled an egg.
The fix was to delete almost all of that code. Instead of pulling particles toward external target positions, I read each particle’s current position every frame, converted it to polar coordinates relative to the galaxy center, and applied two forces directly: a tangential force that spins it into orbit, and a very weak radial spring that nudges it back if it drifts too far inward or outward. Inner particles orbit faster because the tangential speed coefficient scales inversely with radius. Nobody crosses the canvas. Every particle just starts rotating from wherever it already is.
The glow for galaxy mode uses the same concentric stroke circle method from a reference I found: loop from d=0 to d=width, stroke each circle with brightness mapped from high to zero outward. The alpha uses a power curve so it falls off quickly at the edges. The trick is running galaxyGlowT on a separate lerp from galaxyT. The particles start moving into orbit immediately when you press Space, but the ambient halo breathes in much slower, at 0.0035 per frame vs 0.018 for the particle forces. You get the orbital motion first, then the light catches up.
The galaxy center follows wherever you release the mouse. This is made so the galaxy forms where the explosion happens so the particles wrap around the galaxy center in a much more neat way instead of always having the galaxy in the center.
One line in mouseReleased():
galaxyCX = smoothX; galaxyCY = smoothY;
like honestly look how cool this looks now
The third mode came from a reference sketch by professor Jack that drew 1024 noise-driven circles around a fixed ring. Each circle’s radius came from Perlin noise sampled at a position that loops seamlessly around the ring’s circumference without a visible seam, the 999 + cos(angle)*0.5 trick. The output looks like a breathing cell membrane or a pulsar cross-section.
My first implementation was a direct port: 1024 fixed positions on the ring, circles drawn at each one. It worked but the blob had zero relationship to the particles underneath it. It just floated on top like a decal. Press Enter, blob appears. Press Enter again, blob disappears. The particles had nothing to do with any of it.
The version that actually felt right throws out the fixed ring entirely. Instead of iterating 1024 pre-calculated positions, drawMorphOverlay() iterates over the particle array. Each particle draws one circle centered at its own x, y. The noise seed comes from the particle’s live angle relative to morphCX/CY, so each particle carries a stable but slowly shifting petal radius with it as it moves.
let ang = atan2(p.y - morphCY, p.x - morphCX);
let nX = 999 + cos(ang) * 0.5 + cos(lp * TWO_PI) * 0.5;
let nY = 999 + sin(ang) * 0.5 + sin(lp * TWO_PI) * 0.5;
let r = map(noise(nX, nY, 555), 0, 1, height / 18, height / 2.2);
The rendered circle size scales by mt * p.life * proximity. Proximity is how close the particle sits to the ring. Particles clustered at the ring draw full circles. Particles still traveling inward draw small faint ones. When you activate morph mode, the blob coalesces as particles converge. When you deactivate it, the blob tears apart as particles scatter outward, circles traveling with them. The disintegration happens at the particle level, not as a fading overlay.
The core glow stopped rendering at a fixed point too. It now computes the centroid of all particles within 2x the ring radius and renders there. The glow radius scales by count / particles.length, so a sparse ring is dim and a dense ring is bright. The light follows the mass.
Originally I had Space and Enter both cycling through modes in sequence: bio to galaxy to membrane and back. That made no sense for how I actually wanted to use it. Space now toggles bio and galaxy. Enter toggles bio and membrane. If you’re in galaxy and press Enter, galaxyT starts lerping back to zero while morphT starts lerping toward one simultaneously. The cross-fade between two non-bio modes works automatically because both lerps run every frame regardless of which mode is active.
morphAssigned = false triggers the angle re-sort on the next frame, which maps current particle positions to evenly spaced ring angles in angular order. Same fix as the galaxy crossing problem: sort particles by angle from center, sort targets by angle, zip them in order. Nobody crosses the ring.
The sketch now has three fully functional modes with smooth bidirectional transitions. The galaxy holds its own as a visual. The membrane is the most satisfying of the three to toggle in and out of because the disintegration is legible. You can watch individual particles drag pieces of the blob away as they scatter.
I still haven’t solved the performance question on lower-end hardware. The membrane mode in particular runs 80 draw calls per particle at full opacity in additive blending, which is not nothing. My next steps are profiling this properly and figuring out whether the p5 web editor deployment is going to survive it. I’m cautiously optimistic but I’ve been cautiously optimistic before.
I faced many challenges throughout this project. I will list a couple below.
The trails of the particles
The explosion not being strong enough
The behavior of pulling particles
Performance issues
The behavior of particles explosion
The Texture of galaxy (scrapped idea)
and honestly I could go on for days.
The thing that worked the best for me is that I started very early and made a lot of progress early so I had time to play around with ideas. Like the galaxy texture idea for example from the last post, I had time to implement it and also scrap it because of performance issues. I also tried to write some shader code but honestly that went horribly and I didn’t want to learn all of that because the risk margin was high. Say I did learn it and spend days trying to perfect it and end up scrapping the idea. I also didn’t want to generate the whole shaders thing with AI, I actually wanted to at least undestand whats going on.
The most prominent issue was how the prints were going to look like as I didn’t know how to beautifully integrate trails as they looked very odd. I played around with the transparency of the background with many values until I got the sweet spot. My initial 3 modes were attract, condense, and explode but that wouldn’t be conveyed well with the prints so I switched to the modes we have right now.
Reflection
Honestly the user experience is in a better place than I expected it to be at this stage. The core loop, hold to charge, release to detonate, turned out to be one of those interactions that people understand immediately without any instructions, bur I can’t say the same about pressing Enter and Space to toggle around between modes haha. I’ve watched a few people pick it up cold and within thirty seconds they’re already testing how long they can hold before releasing. That’s a good sign. When an interaction teaches itself that quickly, you’ve probably found something worth keeping.
The three modes add a layer of depth that I wasn’t sure would land. Galaxy mode feels the most coherent because the visual logic is obvious: particles orbit a center, a halo breathes outward, the whole thing rotates slowly. Membrane mode is more abstract and I think some people will find it confusing on first contact. The blob emerging from particle convergence reads as intentional once you’ve seen it a few times, but the first time it happens it might just look like a bug. That’s a documentation problem as much as a design problem. A very subtle UI hint, maybe a faint key label in the corner, might do enough work there without breaking the aesthetic.
The transition speeds feel right in galaxy and a little slow in membrane. When you press Enter to leave membrane mode, the blob takes long enough to dissolve that it starts feeling like lag rather than a designed dissolve. I want to tighten the MORPH_LERP value and see if a slightly faster exit reads better while keeping the entrance speed the same. Entering slow, leaving fast, might be the right rhythm for that mode.
Performance is the thing I’m least settled about. On my machine in VS Code the sketch runs clean. The membrane mode specifically concerns me because it runs one draw call per particle per frame in additive blending, and additive blending is expensive in ways that only become obvious at 600 particles so it’s a little bit slower there.
The one thing I genuinely would love to add is audio. Not full sound design, something minimal. A low frequency hum that rises in pitch as charge builds, a short percussive hit on release scaled to the explosion tier. The sketch is very silent right now and I think sound would close a gap in the experience that visuals alone can’t. The charge accumulation in particular has this tension that wants a corresponding audio texture.
The naming situation I mentioned at the start, Melancholic Bioluminescence sounding like a Spotify playlist, has not resolved itself. If anything the addition of galaxy mode and the membrane makes the name less accurate. The name now is GALACTIC
Also yes, AI helped with a lot of the math again. The Keplerian orbital speed scaling, the seamless noise ring sampling, the proximity weighting in the blob. I understand what all of it does now though, which I count as a win. I use AI not do my work, but as a tool that helps me get to what I want as a mentor. I think I am very satisified with this output as I built the architecture, I build the algorithms, I designed everything beforehand and when things felt stuck I used AI as my mentor. I think the section where I used AI the most is filling in a lot of values to for things cus I couldn’t get values that felt nice. Here’s an example below.
My main inspiration came from this video: Instagram
For this project, I chased the feeling of something between a pulsar and a deep-sea creature. The working title became Melancholic Bioluminescence, which sounds like a Spotify playlist but the fun thing about creating projects is having full authority and ownership over everything and its my sketch so I’ll name it that.
The core interaction is simple and satisfying to say out loud: hold your mouse down, energy accumulates, release it to detonate. Hold longer, bigger explosion. That’s the entire loop. What makes it interesting is the texture of the accumulation. Particles spiral inward like a black hole, and the glow resembles energy accumulating within that blackhole.
Before writing a single line, I sketched the architecture on paper. The system has three major layers of responsibility: the global state (are we holding? are we exploding? what’s the charge level?), the particle population (a pool of objects that each manage their own physics), and the vfx (trails, embers, glow pulses, which are short-lived visual elements that don’t need the full particle class). I accumulated my notes and compiled them into a beautiful psuedocode that I can follow, this is me abusing what I learned taking Data Structures and honestly desgining the system beforehand works for me really well
please check the pdf for the psuedcode because there’s this ANNOYING issue that no matter whats the scale of the screenshot I am uploading its always so blurry and small.
I also want to disclose that AI helped me with many mathematical sections within this sketch, I wouldn’t be able to understand the math or get around it on my own I think. But I promise my usage is not excessive or dependent and I actually use it to learn haha
Anyway, I started writing attributes for the particle class and oh boy they added up QUICKLY. Here’s a snippet. I tried assigning random values manually but it was very very hard to find the sweet spot for everything so I used some help from AI to assign the proper values to those attributes and I tweaked them a little bit and got really good results.
A useful frame for interactive generative art is the state machine. This sketch has three primary states that produce visually distinct experiences, and the transitions between them are where most of the design work happened.
Idle state: No mouse interaction. 80 particles drift across the canvas on Perlin noise. Each particle has its own noise offset, frequency, and speed. The result is slow, organic, slightly hypnotic. The palette sits in the 228-288 HSB hue range (blue through violet) and particles breathe gently at a rate of 2 cycles per second. This is the sketch’s resting face, and it needs to be beautiful enough to watch on its own.
Charging state: Mouse held. New particles spawn at the edge of the screen and get pulled toward the cursor which acts as an attractor. Spawn rate accelerates from 1/frame to 18/frame as charge approaches maximum. The vortex arms appear past 8% charge: three logarithmic spirals that rotate faster as charge builds, drawn with beginShape()/vertex() and per-vertex stroke colors that fade toward the outer edge. The glow orb grows around the cursor. Screen rumble starts at 60% charge. Particles near the cursor compress and brighten. The hue of nearby particles shifts toward 305, a hot magenta-violet. Every visual element does the same narrative work: energy is accumulating.
Explosion state: Mouse released. This is tiered across four discrete levels (0 through 3) based on charge thresholds at 0.25, 0.55, and 0.85. Tier 0 is a gentle push. Tier 3 is a white-flash, screen-shake, 800-pixel-radius detonation that spawns up to 70 child particles from split candidates nearest the blast origin. Each particle in blast range gets a force vector calculated from distance falloff (pow(1 - d/blastRadius, 2)), a random rotation drift, and a behavior assignment weighted by proximity to center and charge level. The explosion duration scales with charge, from 1.4 seconds to 4 seconds. The slowdown at high charge gives full-tier explosions a cinematic quality: the cloud expands, holds, then dissipates.
The variation space this produces is wide. A quick series of light taps creates a dotted constellation. Holding in one place while moving slightly creates smeared, comet-like trails. A patient full charge, held long enough to feel the rumble, produces a different kind of satisfaction.
the scariest things about this project were two things braided together: performance under additive blending with 700+ particles, and making the multi-behavior explosion feel coherent rather than random.
Additive blending (blendMode(ADD)) is visually spectacular. Overlapping particles bloom into white rather than muddy brown. The cost is real though: each ellipse composites against everything underneath it. With three ellipses per particle (the outer glow halo, the mid-glow body, and the bright core), plus trail objects, plus embers, a naive implementation at 700 particles hits framerate problems fast. The risk was a beautiful system running at 20fps. I ran many optimization processes but then I migrated to VS code which was MUCH smoother but I don’t know how smart that is going to be because in the end I’m gonna have to embed the sketch in p5.js web editor so it wouldn’t make sense or a difference that it runs smoothy on my device but its laggy on the website.
The mitigation strategy relies on hard caps with graceful degradation. Particles cap at 600 during charging and 700 overall. Trails cap at 1200 objects. Embers die slowly at life -= 0.003 per frame, about 333 frames of life. The three-ellipse draw call per particle uses deliberately low-resolution sizes: the outer halo is s*4, the body s*2, the core s*0.6, where s is typically 1.8-4 pixels. The glow effect comes from accumulationof tiny translucent shapes. The drawGlow() function uses 50 layered ellipses for the cursor glow, each with an alpha under 4, nearly invisible on their own.
For the behavior system, the risk was that five different particle behaviors during explosion would read as a mess of conflicting physics. To test this, I implemented behaviors one at a time and ran the explosion at full charge with only that behavior active, watching whether each produced a readable visual signature. BEHAVE_COMET needed the highest speed and the lowest drag (0.99 vs the standard 0.93-0.97) to produce visible streaks. BEHAVE_BOOMERANG needed the timer offset: if the return force kicked in immediately, particles just wobbled. They needed to actually leave the origin first. BEHAVE_FLUTTER was the most unpredictable and required the dampening multiplier (vx *= 0.985) to prevent runaway acceleration from the oscillating force.
The assignBehavior() method’s probability table weights behavior by charge level and proximity to blast center. Close-in particles at high charge get COMET and SPIRAL; far particles get RADIAL and FLUTTER. This creates a natural visual structure: a dense bright core of fast-moving comets surrounded by a slowly oscillating outer cloud. The explosion has a center and a periphery, which reads as physically plausible even though the physics are entirely invented.
The remaining uncertainty heading into the midterm is whether the vortex spiral arm rendering, which uses nested beginShape()/endShape() with per-vertex stroke calls, holds up on lower-end hardware. The core mechanic, the charge-and-release loop, and the explosion tier system all feel solid. The scary part is mostly tamed.
But there comes another problem. I don’t like the black background so I decided to create a galaxy background. I had a rough idea how to make it but I had to do some research.
Guess what, all of those links were useless. I found nothing of help but I didn’t want to give up. so I found this reddit post and I found this page and I follwed the principles and methods in the article to create something cool.
I tried to upload the gif of the animated image but I got this error so I will just upload a screenshot unfortunately.
I really dont know why the resolution is so low my monitor is 4k resolution and honestly it’s too late for me to worry about this. Anyway, I would love to go with the galaxy design but unfortunately it lags like HELL even on VS code, maybe I’ll book office hours and see how I can troubleshoot this.
my next steps for this is to figure out the background and also try to replicate the main inspiration video because right now everything feels flat and I am starting to hate it.
My inspiration comes from Memo Akten’s Simple Harmonic Motion 8-9. I wanted to build something that felt alive on screen. Waves have always fascinated me, specifically the way two simple oscillations combine into something unexpectedly complex. I used the principles of adding waves together such that: peak + peak = higher peak, trough + trough = lower trough, and peak + trough cancel each other.
Please move mouse around and click around the sketch for special effects.
I started with the simplest possible thing: a single sine wave drawn as dots across the canvas.
I added a second wave with a different frequency and a phase offset of PI, so it starts on the opposite side of the cycle from wave one. The two waves drift in and out of sync as time moves forward. Wave two has a slightly higher frequency and a smaller amplitude, so it has its own distinct character.
This is where things got interesting. I added a third wave that is the sum of the first two. When the two source waves push in the same direction, the result amplifies. When they oppose each other, they cancel out. The yellow interference wave is the visual record of that conversation between the two.
I replaced the solid background() call with a semi-transparent rectangle drawn each frame. The old frames fade slowly instead of disappearing instantly.
The two amplitudes breathe at different rates, so they are never in sync with each other. The interference wave gets dramatically more expressive as a result, going nearly flat at times and spiking wide at others.
I switched to HSB color mode and tied the hue and brightness of each point to its position in the wave cycle.
let hue1 = map(sin(x * 0.01 + t * 0.5), -1, 1, 160, 220);
let bright1 = map(abs(y1), 0, amp1, 60, 100);
I expanded from two base waves to four, each with its own frequency, speed, phase, and breathing amplitude. I also added two partial interference sums alongside the full sum of all four.
The frequency ratios across the four waves are close to harmonic but slightly off, so the pattern never fully repeats. There is always something new happening somewhere on the canvas.
let yA = ys[0] + ys[1];
let yB = ys[2] + ys[3];
let yFull = ys[0] + ys[1] + ys[2] + ys[3];
At this point the draw() loop was getting hard to read. I pulled the repeating logic into dedicated functions. All wave parameters moved into a waveDefs array of objects. I also moved the array definition inside setup().
function waveY(x, def, amp) { ... }
function breathingAmp(i) { ... }
function driftHue(x, hueMin, hueMax, freqX, freqT) { ... }
function drawWavePoint(x, y, centerY, hue, sat, maxAmp, weight, alpha) { ... }
function drawSumPoint(x, y, centerY, maxDisplace, hueMin, hueMax, sat, weight, alpha) { ... }
I added a mousePull() function that bends each wave point toward the cursor. The pull strength falls off with distance, reaching zero at 200 pixels away. Moving the mouse slowly across the canvas bends the waves toward it in a way that feels physical. The effect fades naturally so it never feels abrupt. The final step was a Ripple class. Clicking spawns a ring that expands outward from the click position and displaces any wave point it passes through. The ring has a bandwidth of 40 pixels. Points inside that band get displaced, everything outside it is untouched. The ripple fades as it expands and gets removed from the array once it exceeds its maximum radius. Multiple ripples can coexist and their displacements stack on top of each other.
function mousePull(x, baseY, centerY) {
let dist = sqrt(dx * dx + dy * dy);
let influence = constrain(map(dist, 0, 200, 60, 0), 0, 60);
return dy * (influence / max(dist, 1)) * -1;
}
class Ripple {
constructor(x, y) {
this.radius = 0;
this.speed = 4;
this.maxRadius = 300;
this.strength = 55;
}
influence(px, py) {
let ring = abs(dist - this.radius);
if (ring > 40) return 0;
let fade = map(this.radius, 0, this.maxRadius, 1, 0);
let falloff = map(ring, 0, 40, 1, 0);
return sin(ring * 0.3) * this.strength * fade * falloff;
}
}
For future improvements, I want to make the waves responsive to music/notes. I think this can be done by using Fast Fourier Transform which I’ve used and written a paper about before in one of my INTRO TO IM projects. it would work by processing the whole audio file once then storing the data in a queue and mapping each frequency band to an intersection between waves. I really wanna try this but it seems a little bit challenging so I didnt implement it in this sketch.
This sketch is a kaleidoscopic illustration of movers and attractors. My main inspiration is a combination of the picture above and a mix of effects I used in one of my motion graphics/VFX projects. I wanted to recreate a sample that captures both feelings at once.
I started this sketch by placing circular attractors as shown in the image.
I wrote code that creates a circular arrangement of attractor points around a center position.
for (let i = 0; i < numAttractors; i++) {
let angle = (TWO_PI / numAttractors) * i;
let x = centerX + cos(angle) * attractorRadius;
let y = centerY + sin(angle) * attractorRadius;
attractors.push(new Attractor(x, y, 20));
}
}
This loop divides the circle into segments, each iteration multiplies by i to get the angle for that specific attractor. For x and y positions, I use polar-to-cartesian coordinate conversion as shown in the code.
Then I added movers and I applied the forces to the movers such that their position is affected by the attractors.
So basically, the kaleidoscope effect happens because every single object gets drawn (numAttractors) times instead of just once. The trick is that before drawing each copy, the code rotates the entire coordinate system around the center of the canvas by increments of 60 degrees (since 360 deg ÷ 6 = 60 deg). It does this by moving the origin to the canvas center, rotating, then moving it back, and finally drawing the object at its actual position. But because the whole coordinate system has been rotated, what you actually see is the object appearing in six different spots arranged symmetrically around the center, like looking through a kaleidoscope. The cool part is that the physics simulation itself, only happens once for each object, but visually you see six reflections of everything. So when a mover orbits an attractor, all six of its mirror images orbit simultaneously.
For example, the number of movers in this sketch is 1, but it gets reflected 5 times
Here’s the code responsible for the kaliedoscope effect
for (let i = 0; i < symmetryFold; i++) {
push();
translate(width / 2, height / 2); // move origin to center
rotate((TWO_PI / symmetryFold) * i); // rotate by incremental angle
translate(-width / 2, -height / 2); // move origin back
circle(this.position.x, this.position.y, size); // draw at original position
pop();
}
I then made some really interesting changes here that make the pattern way more complex and controlled. I added this clever touch of four “corner attractors” placed at each corner of the canvas with higher mass , which act like gravitational anchors that influence the overall flow and create an effect of repulsion. I also added a visibility toggle (showAttractorsRepeller) so I can hide the attractors if I just want to see the trails. Speaking of trails, I changed the background to fade super slowly with background(0, 1) instead of clearing completely each frame, which creates these motion trails that build up over time. And finally, I made the movers wrap around the screen edges, if one goes off the right side it reappears on the left, which keeps the pattern continuous and prevents movers from escaping the canvas entirely.
Then I hit the jackpot. By changing one of the corner attractors mass, I create really interesting kaleidoscopic effects as shown in the gif below
Then by playing with the number of attractors I achieve really compelling visual effects like this
Sketch
To get the most out of this sketch, please manipulate the parameters I indicated at the top of the code. There’s something so super satisfying with watching those patterns slowly get created.
The part I’m most proud of is how I implemented the radial symmetry to create that kaleidoscope effect. I only spawn a couple of movers in one “wedge” of the canvas, like a single slice of pizza, and then mirror them automatically across however many symmetry folds I’ve set instead of simulating physics for dozens of particles. The magic happens in the show() methods where I loop through each symmetry fold, rotate the coordinate system incrementally around the canvas center, and draw the same object multiple times at different rotational positions. So when I have 10 attractors arranged in a circle, I also get 10-way symmetry, meaning my 2 actual movers appear as 20 visual copies. It’s incredibly efficient because the physics calculations only happen once per real mover, but the visual output looks way more complex and mesmerizing. The whole system is tied together by making symmetryFold equal to numAttractors.
Moving forward, I’d love to add some interactivity so I can manipulate the system in realtime, maybe clicking to add new attractors or repellers, or using the mouse to adjust the gravitational constant and see how it affects the flow. I’m also thinking about implementing color gradients based on velocity or distance from the center, which would add another layer of visual depth to the trails. I did try this actually but it looked so bad I had to remove it. I also tried making the hue based on the velocity but that also looked bad. It would be cool to experiment with different symmetry modes too, like switching between radial symmetry and bilateral symmetry on the fly, or even adding a mode where the symmetry fold changes dynamically over time to create evolving patterns. Finally, adding some kind of preset system where I can save and load different attractor configurations would make it way easier to explore different aesthetic possibilities without manually tweaking parameters every time.
What inspired this project is my fish, Abdulfattah, a Betta fish that was gifted to me from a very dear person to my heart.
This sketch mimics natural fish movement when it spots food. The user moves the mouse around and upon clicking you essentially drop a fish food pellet, and the fish mimics natural movement and acceleration towards food.
I first started t project by adding a background I found online
Blue water surface template in cartoon style illustration
then I made a rectangle that will later be a fish to start simulating it’s movement.
then I wrote very simple code with if statements just as a base for my fish movement.
then I updated my code to lerp (linear interpolation) towards the mouse.
After that I started implementing dropping fish pellets, I started with creating a simple function to spawn pellets with an array of circles.
let circles[];
//in draw
for (let circle of circles) {
fill(139, 69, 19); // brown
noStroke();
ellipse(circle.x, circle.y, 20, 20);
function mousePressed() {
circles.push({x: mouseX, y: mouseY});
}
Then I added a sinking motion for the pellets with a slight drift using the sin function to simulate natural waves pushing pellets around as they are sinking with a random angle for variation.
// draw food pellets
for (let i = circles.length - 1; i >= 0; i--) {
let circle = circles[i];
// make circle float downwards
circle.y += circle.speed;
// increment the angle for sin
circle.angle += 0.05;
// subtle drift for food pelletes
let drift = sin(circle.angle) * 20;
// draw circles
fill(139, 69, 19);
noStroke();
ellipse(circle.x + drift, circle.y, 20, 20);
then I edited the code to make the rectangle follow the pellets instead of the mouse. For error handling, the pellets are put in a stack such that the rectangle eats the pellets using a queue as a data structure following the FIFO (first in last out) principle.
A challenge I faced:
As shown in the previous gif, there was a problem where the rectangle can’t eat the food because the pellets are drifting and sinking. This is happening because the rectangle is trying to go the position of that circle but it doesn’t account for the drifting and sinking, therefore, its more like it’s tracing the pellet rather than trying to catch it.
The way I tackled this challenge is also a highlight of the code that I’m proud of.
.I fixed this by predicting where each pellet would be 10 frames ahead, accounting for sinking and horizontal drift. I calculated the direction vector and euclidean distance to this predicted target, then normalized it to apply acceleration forces. The velocity builds gradually but it’s not fully smooth yet but I’ll get to that later. I multiplied velocity by 0.92 each frame for friction, cap the maximum speed, then update position. When the fish gets within 30 pixels of a pellet, it gets removed from the queue with shift() and reduce velocity by 70%. This creates a deceleration effect before accelerating toward the next pellet.
function followCircles(){
// if there are circles, follow the first one following FIFO principle
if (circles.length > 0) {
let target = circles[0];
// predict where the pellet will be
let futureY = target.y + target.speed * 10;
let futureAngle = target.angle + 0.03 * 10;
let futureDrift = sin(futureAngle) * 1.5;
let targetX = target.x + futureDrift; // i add the predicted position here so the fish can catch the food
let targetY = futureY;
// calculate direction to predicted position
let dx = targetX - x;
let dy = targetY - y;
let distance = dist(x, y, targetX, targetY); // calculate the eucilidian distance of the fish and the pellet
// normalize direction and apply acceleration
if (distance > 0) {
vx += (dx / distance) * acceleration;
vy += (dy / distance) * acceleration;
}
// apply friction for more natural movement
vx *= friction;
vy *= friction;
// limit speed
let speed = dist(0, 0, vx, vy);
if (speed > maxSpeed) {
vx = (vx / speed) * maxSpeed;
vy = (vy / speed) * maxSpeed;
}
// update position with velocity
x += vx;
y += vy;
// check if rectangle is touching the circle
let actualDistance = dist(x, y, target.x + target.drift, target.y);
if (actualDistance < 30) {
circles.shift(); // eat the circle
// reduce velocity when eating
vx *= 0.3;
vy *= 0.3;
}
} else {
// slow down when no target
vx *= 0.9;
vy *= 0.9;
}
}
another problem I faced was the fish was getting stuck around the corners but I easily fixed that but implementing a function that lets the fish wander using perlin noise (Thanks professor Jack!!)
I want to have a simulation of the background such that it actually simulates fluids and looks like water. I also have 3 more fish in the tank that are Abdulfattah’s friends that I want to add, they always steal his food so it would be more realistic that way. Moreover I want to have a bigger canvas so I can add object you naturally find in the ocean or the one’s I have in my fish tank, and an algorithm that makes the fish occasionally hide behind those objects. Lastly, I want an algorithm where sometimes the fish just rests in the tank doing nothing, which would add more realism to the sketch.
This chapter hit me hard. Flake asks the question I’ve been circling around for years: why can’t we predict everything if we understand the parts? The ant colony example nails it. You can study individual ants all day long. You can catalog their behaviors, map their neural pathways, document their castes. You still won’t predict the emergent sophistication of millions of them working together.
I love how Flake frames computation as nature’s language. We’ve been so focused on dissecting things that we forgot to ask “what does this do?” instead of “what is this?” That shift feels enormous. A duck isn’t just feathers and bones. A duck migrates, mates, socializes, adapts. The doing matters as much as the being.
The pdf’s structure fascinates me. Fractals lead to chaos, chaos leads to complex systems, complex systems lead to adaptation. Everything connects. I’ve read excerpts on chaos theory. I’ve read excerpts on evolution. I’ve never seen someone draw the lines between them so clearly. Simple rules, iterated over time, create everything from snowflakes to stock markets.
The timing matters too. Flake wrote this in 1998, right when computers stopped being tools and became laboratories. We could finally simulate systems too complex to solve analytically. That changed everything. Meteorologists, economists, biologists: they all started speaking the same computational language.
What gets me is the humility baked into this approach. Reductionism promised we could know everything by breaking it down far enough. Flake shows us the limits. Some things are incomputable. Some systems defy long-term prediction. Understanding quarks doesn’t help a doctor diagnose patients. Understanding individual neurons doesn’t explain consciousness.