xxxxxxxxxx
126
let points = [];
let linePoints = [];
let lines = [];
let head;
let tempBody;
let tempArm;
const numPoints = 12;
const minDistance = 30;
const numConnections = 6;
const padding = 20;
function setup() {
createCanvas(170, 350);
generatePoints();
generateBody();
}
function draw() {
background(220);
// draw body
stroke(0);
noFill();
beginShape();
const firstPoint = tempBody[0];
const lastPoint = tempBody[tempBody.length - 1];
curveVertex(firstPoint.x, firstPoint.y);
tempBody.forEach(p => {
curveVertex(p.x, p.y);
});
curveVertex(lastPoint.x, lastPoint.y);
endShape();
beginShape();
const firstPoint1 = tempArm[0];
const lastPoint1 = tempArm[tempArm.length - 1];
curveVertex(firstPoint1.x, firstPoint1.y);
tempArm.forEach(p => {
curveVertex(p.x, p.y);
});
curveVertex(lastPoint1.x, lastPoint1.y);
endShape();
// Draw the points
points.forEach(p => {
fill(0);
noStroke();
circle(p.x, p.y, 4);
});
fill(220);
stroke(0);
strokeWeight(2);
circle(head.x, head.y, 20);
}
function generatePoints() {
for (let i = 0; i < numPoints; i++) {
let valid = false;
let candidate;
// Try generating a valid candidate point
while (!valid) {
valid = true;
candidate = createVector(random(padding, width - padding),
random(padding, height - padding));
// Check the minimum distance to existing points
for (let j = 0; j < points.length; j++) {
const existingPoint = points[j];
const distance = p5.Vector.dist(candidate, existingPoint);
if (distance < minDistance) {
valid = false;
break;
}
}
}
points.push(candidate);
}
}
function generateBody() {
const headPoint = floor(random(points.length));
head = points[headPoint];
points.splice(headPoint, 1);
let currentPoint = head;
let body = [];
for(let i = 0; i < 7; i++) {
body.push(currentPoint);
currentPoint = getNearest(currentPoint);
}
lines.push(body);
tempBody = body;
let arm = [];
currentPoint = random(body);
for(let i = 0; i < 3; i++) {
arm.push(currentPoint);
currentPoint = getNearest(currentPoint);
}
lines.push(arm);
tempArm = arm;
}
function getNearest(currentPoint) {
let minDist = 1000;
let nearestPoint;
let npIndex;
points.forEach((p, i) => {
const distance = currentPoint.dist(p);
if ((distance > 0) && (distance < minDist)) {
minDist = distance;
nearestPoint = p;
npIndex = i;
}
});
points.splice(npIndex, 1);
return nearestPoint;
}