xxxxxxxxxx
75
// Create a random walker with dynamic probabilities. For example, can you give it a 50 percent chance of moving in the direction of the mouse?
let walkers = [];
class Walker {
constructor() {
this.pos = createVector(random(width), random(height));
this.vel = createVector(0, 0);
}
update() {
let r = random(1);
let mous = createVector(mouseX, mouseY);
// 5% of the time have the walkers move in the
// direction of the mouse, otherwise move randomly
if (r < .5) {
let dist = .05 * (this.pos.dist(mous))
if (dist < 1) {
dist *=-1
}
if (this.pos.x < mous.x) {
this.vel.x = dist;
} else if (this.pos.x > mous.x) {
this.vel.x = -dist;
}
if (this.pos.y < mous.y) {
this.vel.y = dist;
} else if (this.pos.y > mous.y) {
this.vel.y = -dist;
}
this.pos.add(this.vel);
} else {
this.vel = createVector(random(-2, 2), random(-2, 2));
this.pos.add(this.vel);
}
}
show() {
// style the circle
stroke(255);
fill(25);
strokeWeight(4);
// draw the circle
circle(this.pos.x, this.pos.y, 10);
}
}
function setup() {
createCanvas(400, 400);
}
function draw() {
background(20);
let chance = random(100);
// if there's less than 100 walkers, add one more
if (chance < 10 && walkers.length < 100) {
walkers.push(new Walker());
}
// update and draw all the walkers in the array
for (let w = 0; w < walkers.length; w++) {
walkers[w].update();
walkers[w].show();
}
}