xxxxxxxxxx
69
let points = [];
let x = 200;
let y = 200;
function setup() {
createCanvas(400, 400);
// Create random points and add them to the array
for (let i = 0; i < 5; i++) {
let pnt = createVector(random(0, width), random(0, height));
points.push(pnt);
}
}
function draw() {
background(220);
strokeWeight(5);
// Loop through the points array and draw lines between adjacent points
for (let i = 0; i < points.length - 1; i++) {
let currentPoint = points[i];
let nextPoint = points[i + 1];
line(currentPoint.x, currentPoint.y, nextPoint.x, nextPoint.y);
}
// Update the position of the last point based on mouse coordinates
points[points.length - 1].x = x;
points[points.length - 1].y = y;
// Repulsion force between points that are too far apart
const repulsionForce = 0.05;
for (let s = 0; s < points.length - 1; s++) {
let currentPoint = points[s];
let nextPoint = points[s + 1];
// Calculate the distance between current and next point
let distance = dist(currentPoint.x, currentPoint.y, nextPoint.x, nextPoint.y);
if (distance > 65) {
// Calculate the direction vector
let direction = p5.Vector.sub(nextPoint, currentPoint).normalize();
// Calculate the amount by which to move the points
let movement = direction.mult(repulsionForce * (distance - 65));
// Move the current and next points
currentPoint.add(movement);
nextPoint.sub(movement);
}
if (keyIsDown(LEFT_ARROW)) { // Fixed key comparison using keyCode
x -= 1;
}
if (keyIsDown(RIGHT_ARROW)) { // Fixed key comparison using keyCode
x += 1;
}
if (keyIsDown(UP_ARROW)) { // Fixed key comparison using keyCode
y -= 1;
}
if (keyIsDown(DOWN_ARROW)) { // Fixed key comparison using keyCode
y += 1;
}
}
}