xxxxxxxxxx
84
// Author: Aaron
// title: Ant scattering simulation.
let ants = [];
let velocityIncrease = 2; // Amount to increase ant velocity when clicked
let velocityDecreaseTimer = 0; // Timer to gradually slow down the ants
let slowdownDuration = 60 * 5; // Duration of slowdown in frames (3 seconds at 60 frames per second)
function setup() {
createCanvas(800, 600);
background(214,196,183);
// Initialize a population of ants
for (let i = 0; i < 200; i++) {
let ant = new Ant(random(width), random(height));
ants.push(ant);
}
}
function draw() {
for (let ant of ants) {
ant.update();
ant.display();
}
// Decrease velocity timer
if (velocityDecreaseTimer > 0) {
velocityDecreaseTimer--;
if (velocityDecreaseTimer === 0) {
// Reset ant velocities to their original values
for (let ant of ants) {
ant.resetVelocity();
}
}
}
}
function mouseClicked() {
// Increase the velocity of all ants when clicked
for (let ant of ants) {
ant.velocity.mult(velocityIncrease);
}
// Start the velocity decrease timer
velocityDecreaseTimer = slowdownDuration;
}
class Ant {
constructor(x, y) {
this.position = createVector(x, y);
this.originalVelocity = p5.Vector.random2D().mult(random(2, 4)); // Random initial velocity
this.velocity = this.originalVelocity.copy(); // Store the current velocity
}
update() {
// Update ant's position based on velocity
this.position.add(this.velocity);
// Wrap the ant around the screen
this.position.x = (this.position.x + width) % width;
this.position.y = (this.position.y + height) % height;
}
display() {
// Draw the ant as a small circle
fill(0);
ellipse(this.position.x, this.position.y, 10, 10);
line(
this.position.x + 1,
this.position.y + 1,
this.position.x + 6,
this.position.y + 6
);
}
// Reset ant's velocity to the original value
resetVelocity() {
this.velocity = this.originalVelocity.copy();
}
}