xxxxxxxxxx
/*
Spectrum rays
Controls:
- Hold mouse button to add particles.
- Move mouse along x-axis to change shapes threshold.
Author:
Jason Labbe
Site:
jasonlabbe3d.com
*/
var bobs = [];
var fRate = 0;
var threshold;
function setup() {
createCanvas(1000, 600);
colorMode(HSB, 255);
mouseX = width / 2;
}
function draw() {
// Spawn a new Bob.
if (frameCount % 5 == 0) {
bobs.push(new Bob(
-50, random(height / 2 -50, height / 2 + 50),
random(1, 2), 0));
}
// Spawn Bobs triggered from user.
if (mouseIsPressed) {
if (frameCount % 2 == 0) {
bobs.push(new Bob(mouseX, mouseY, random(2, 3), 0));
}
}
background(0);
threshold = map(constrain(mouseX, 0, width), 0, width, 0, 200);
for (let i = bobs.length - 1; i > -1; i--) {
let bob = bobs[i];
// Have the Bob always steer to the height's center.
let vec = new p5.Vector(bob.pos.x, bob.pos.y);
vec.sub(bob.pos.x, height / 2);
vec.normalize();
vec.mult(-0.15);
bob.vel.add(vec);
bob.pos.add(bob.vel);
bob.pos.x += bob.vel.x;
// Kill Bob if it goes out of bounds.
if (bob.pos.y < -100 || bob.pos.x < -100 || bob.pos.x > width + 100) {
bobs.splice(i, 1);
}
}
for (let i = 0; i < bobs.length; i++) {
let bob = bobs[i];
// Bob's position define's its hue.
let h = map(bob.pos.x, 0, width, 0, 255);
// Display Bob!
stroke(h, 255, 255, 125);
strokeWeight(3);
point(bob.pos.x, bob.pos.y);
// Look for Bob's neighbors.
let neighbors = [];
for (let j = 0; j < bobs.length; j++) {
if (neighbors.length > 8) {
break;
}
if (i == j) {
continue;
}
let d = dist(bob.pos.x, bob.pos.y, bobs[j].pos.x, bobs[j].pos.y);
if (d < threshold) {
neighbors.push(bobs[j]);
}
}
// If Bob has neighbors then draw a shape from them.
if (neighbors.length > 0) {
strokeWeight(0.5);
stroke(h, 255, 255, 50);
fill(h, 255, 255, 50);
beginShape();
curveVertex(bob.pos.x, bob.pos.y);
for (let j = 0; j < neighbors.length; j++) {
curveVertex(neighbors[j].pos.x, neighbors[j].pos.y);
}
endShape(CLOSE);
}
}
// Periodically update the frame rate.
if (frameCount % 10 == 0) {
fRate = frameRate();
}
// Display debugging info.
noStroke();
fill(255);
let debugInfo = "".concat(
"fps: ", nf(fRate, 2, 2), "\n",
"threshold: ", nf(threshold, 2, 2));
text(debugInfo, 20, 20);
text("(Hold mouse down to add new particles)", 20, height - 20);
}
// It's Bob!
function Bob(x, y, vx, vy) {
this.pos = new p5.Vector(x, y);
this.vel = new p5.Vector(vx, vy);
}