xxxxxxxxxx
86
// Define an array to store the fireflies
let fireflies = [];
function setup() {
createCanvas(400, 400);
// Create a specified number of fireflies and add them to the array
for (let i = 0; i < 50; i++) {
let x = random(width);
let y = random(height);
let firefly = new Firefly(x, y);
fireflies.push(firefly);
}
}
function draw() {
background(0);
// Define the target position as the mouse pointer
let target = createVector(mouseX, mouseY);
// Loop through each firefly and update its behavior and display
for (let firefly of fireflies) {
firefly.update(target);
firefly.display();
}
}
// Define the Firefly class
class Firefly {
constructor(x, y) {
this.position = createVector(x, y);
this.velocity = createVector(0, 0);
this.acceleration = p5.Vector.random2D();
this.maxSpeed = 2;
this.maxForce = 0.3;
this.radius = random(2, 4);
this.phase = random(TWO_PI); // Randomize the phase of flashing
this.frequency = random(0.1, 0.5); // Randomize the flashing frequency
this.amplitude = random(5, 20); // Randomize the flashing amplitude
}
// Apply a force to the firefly
applyForce(force) {
this.acceleration.add(force);
}
// Update the firefly's position and behavior
update(target) {
// Simulate the flashing behavior
this.angle = this.phase + this.amplitude * sin(this.frequency * millis() * 0.001);
// Move away from the mouse when it's within a certain distance
let desired = p5.Vector.sub(target, this.position);
let d = desired.mag();
if (d < 50) {
desired.setMag(this.maxSpeed);
desired.mult(-1);
let steer = p5.Vector.sub(desired, this.velocity);
steer.limit(this.maxForce);
this.applyForce(steer);
}
// Apply acceleration to the velocity
this.velocity.add(this.acceleration);
this.velocity.limit(this.maxSpeed);
this.position.add(this.velocity);
this.acceleration.mult(0); // Reset acceleration
// Wrap around the canvas edges
if (this.position.x < 0) this.position.x = width;
if (this.position.x > width) this.position.x = 0;
if (this.position.y < 0) this.position.y = height;
if (this.position.y > height) this.position.y = 0;
}
// Display the firefly
display() {
noStroke();
fill(255, 255, 0, 150); // Yellow with transparency
let x = this.position.x + this.radius * cos(this.angle)*3;
let y = this.position.y + this.radius * sin(this.angle)*3;
ellipse(x, y, this.radius * 2);
}
}