xxxxxxxxxx
75
class Walker {
constructor() {
this.x = width / 2;
this.y = height / 2;
// Initialize the creature shape with random vertices
this.numVertices = 10;
this.creatureShape = [];
for (let i = 0; i < this.numVertices; i++) {
this.creatureShape.push(createVector(random(-20, 20), random(-20, 20)));
}
}
step() {
// Calculate a random number between 0 and 1
let r = random(1);
// Calculate a random-varying probability of moving towards a mouse
let probabilityToMouse = random(1);
let x = this.x;
let y = this.y;
if (r < probabilityToMouse) {
// Move towards the mouse
let stepX = (mouseX - x) * 0.04;
let stepY = (mouseY - y) * 0.04;
x += stepX;
y += stepY;
} else {
// Move randomly
let stepX = random(-10, 10);
let stepY = random(-10, 10);
x += stepX;
y += stepY;
}
// Constrain the walker within the canvas
x = constrain(x, 0, width);
y = constrain(y, 0, height);
this.x = x;
this.y = y;
}
display() {
this.updateBounds();
// Draw the walker as a constantly morphing creature shape
background(220);
translate(this.x, this.y);
beginShape();
for (let i = 0; i < this.numVertices; i++) {
let vertexX = this.creatureShape[i].x;
let vertexY = this.creatureShape[i].y;
vertex(vertexX, vertexY);
}
endShape(CLOSE);
}
updateBounds() {
// Randomly update the creature shape
for (let i = 0; i < this.numVertices; i++) {
this.creatureShape[i].x += random(-1, 1);
this.creatureShape[i].y += random(-1, 1);
}
}
}
let walker;
function setup() {
createCanvas(400, 400);
background(220);
walker = new Walker();
}
function draw() {
walker.step()
walker.display()
}