xxxxxxxxxx
//circulation
const agentColor = new Uint8Array([0, 0, 0]);
const agentsNum = 1000;
const sensorOffset = 10;
const sensorAngle = 45;
const turnAngle = 60;
let agents;
function setup() {
angleMode(DEGREES);
createCanvas(windowWidth, windowHeight, WEBGL);
stroke("gray");
strokeWeight(1);
g = createGraphics(1000, 1000);
g.pixelDensity(1);
agents = new Agents();
}
function draw() {
clear();
texture(g);
torus(360, 270);
const camAngle = frameCount / 5;
const camDist = 640;
const x=camDist*cos(camAngle);
const y=camDist*sin(camAngle);
camera(x, y, 0, 0, 0, mouseY - height / 2, 0, 0, 1);
g.background(255, 10);
g.loadPixels();
for (let i = 10; i--; ) {
agents.update();
}
g.updatePixels();
}
function mouseClicked(){
agents = null;
agents = new Agents();
}
class Agent {
constructor() {
this.x = width / 2;
this.y = height / 2;
this.dir = random(360);
}
updateDirection() {
const right = this.sense(+sensorAngle);
const center = this.sense(0);
const left = this.sense(-sensorAngle);
const threeWays = [left, center - 1, right];
const minIndex = threeWays.indexOf(min(threeWays));
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 + g.width) % g.width;
y = (y + g.height) % g.height;
const index = (x + y * g.width) * 4;
return g.pixels[index];
}
updatePosition() {
this.x += cos(this.dir);
this.y += sin(this.dir);
this.x = (this.x + g.width) % g.width;
this.y = (this.y + g.height) % g.height;
const index = floor(this.x) + floor(this.y) * g.width;
g.pixels.set(agentColor, index * 4);
}
}
class Agents {
constructor() {
this.agents = Array(agentsNum)
.fill()
.map((e) => new Agent());
}
update() {
this.agents.forEach((e) => e.updateDirection());
this.agents.forEach((e) => e.updatePosition());
}
}