xxxxxxxxxx
44
/* Create a sketch in which a small 2D element travels erratically from one moment to the next, leaving a trail across the canvas as it moves.
At every timestep, it should update its current position with a small random displacement in both X and Y. */
let currentX;
let currentY;
let lastX;
let lastY;
function setup() {
createCanvas(400, 400);
background(255);
strokeWeight(3);
currentX = lastX = width / 2;
currentY = lastY = height / 2;
}
function draw() {
background(255,1);
let randomX = random(-20, 20);
let randomY = random(-20, 20);
currentX = randomX + lastX;
currentY = randomY + lastY;
if (currentX > width) {
currentX = currentX - 2 * randomX;
}
if (currentX < 0) {
currentX = currentX - 2 * randomX;
}
if (currentY > height) {
currentY = currentY - 2 * randomY;
}
if (currentY < 0) {
currentY = currentY - 2 * randomY;
}
line(lastX, lastY, currentX, currentY);
lastX = currentX;
lastY = currentY;
}