xxxxxxxxxx
// Inspired by Jason
// https://softologyblog.wordpress.com/2019/04/11/physarum-simulations/
OPC.button("btoButton", "back to origin");
let agents;
const agentsAmount = 1500;
const sensorOffset = 10;
// I made the big difference between the angle detected by the sensor and the actual turning angle. As a result, the network became unstable.
const sensorAngle = 20;
const turnAngle = 40;
function setup() {
angleMode(DEGREES);
createCanvas(720, 720);
pixelDensity(1);
agents = new Agents();
}
function buttonPressed() {
agents = new Agents();
}
function mouseDragged() {
stroke("blue");
strokeWeight(50);
line(pmouseX, pmouseY, mouseX, mouseY);
}
function draw() {
background(255, 10);
loadPixels();
for (let i = 10; i--; ) agents.update();
updatePixels();
}
class Agent {
constructor() {
this.x = width / 2;
this.y = height / 2;
this.dir = random(360);
this.detectedPheromone = 0;
}
updateDirection() {
const left = this.sense(-sensorAngle);
const center = this.sense(0);
const right = this.sense(+sensorAngle);
// The meaning of "center - 1" is to give priority to center if left, center, and right are all the same.
const threeWays = [left, center - 1, right];
const m = min(threeWays);
this.detectedPheromone = m;
const minIndex = threeWays.indexOf(m);
this.dir += turnAngle * (minIndex - 1);
}
sense(dirOffset) {
const angle = this.dir + dirOffset;
let x = floor(this.x + sensorOffset * cos(angle));
let y = floor(this.y + sensorOffset * sin(angle));
x = (x + width) % width;
y = (y + height) % height;
const index = (x + y * width) * 4;
return pixels[index];
}
updatePosition() {
this.x += cos(this.dir);
this.y += sin(this.dir);
this.x = (this.x + width) % width;
this.y = (this.y + height) % height;
const index = floor(this.x) + floor(this.y) * width;
pixels.set([0, 0, 256 - this.detectedPheromone], index * 4);
}
}
class Agents {
constructor() {
this.agents = Array(agentsAmount)
.fill()
.map((e) => new Agent());
}
update() {
this.agents.forEach((e) => e.updateDirection());
this.agents.forEach((e) => e.updatePosition());
}
}