Click for new tunnels. Press any key to save screenshots.
A fork of Ant Colony Simulation by Richard Bourne
xxxxxxxxxx
const antsNum = 500;
const sensorOffset = 16;
const clockwise = Math.PI / 4;
const counter = -Math.PI / 4;
let maxDistSq;
setup = () => {
createCanvas(1112, 834);
pixelDensity(1);
background(0); // Initialize trail
maxDistSq = (width / 2)**2;
ants.init();
};
mousePressed = () => ants.init();
draw = () => {
background(0, 12); // Update trail
loadPixels();
for (let i = 5; i--; ) {
ants.updateAngle();
ants.updatePosition();
}
updatePixels();
};
const ant = () => ({
x: 0,
y: 0,
angle: random(TWO_PI),
});
const ants = {
ants: [],
init() {
this.ants.length = 0;
for (let i = antsNum ; i--; ) this.ants.push(ant());
},
smell(a, d) {
const aim = a.angle + d,
x = a.x + sensorOffset * cos(aim),
y = a.y + sensorOffset * sin(aim);
if (a.x ** 2 + a.y ** 2 > maxDistSq) return 0;
const index = ((0 | x + width / 2) + (0 | y + height / 2) * width) * 4;
return pixels[index];
},
updateAngle() {
for (const a of this.ants) {
const right = this.smell(a, clockwise),
center = this.smell(a, 0),
left = this.smell(a, counter);
if (center > left && center > right){ /* Carry on straight */ }
else if (left < right) a.angle += clockwise;
else if (left > right) a.angle += counter;
}
},
updatePosition() {
for (const a of this.ants) {
a.x += cos(a.angle);
a.y += sin(a.angle);
if (a.x ** 2 + a.y ** 2 > maxDistSq) a.x = a.y = 0;
let index = ((0 | a.x + width / 2) + (0 | a.y + height / 2) * width) * 4;
pixels[index] = pixels[++index] = pixels[++index] = 255;
}
},
};