xxxxxxxxxx
56
function snap(s, t, r) {
const dx = s[0] - t[0];
const dy = s[1] - t[1];
const d2 = dx*dx + dy*dy;
if(d2 > r * r) {
const a = Math.atan2(dy, dx);
let x = -Math.cos(a) * r + s[0];
let y = -Math.sin(a) * r + s[1];
return [x,y];
}
return t;
}
class DotString {
constructor(n, r, ix=0, iy=0) {
this.xs = Array.from({ length: n }, () => [ix, iy]);
this.old = this.xs;
this.r = r;
}
move(x,y) {
this.old = this.xs.map(p => p.map(x => x));
let prev;
this.xs = this.xs.map((c,i) => {
prev = i == 0 ? [x,y] : snap(prev, c, this.r);
return prev;
});
}
render() {
stroke(255);
this.xs.reduce(([x1,y1], [x2,y2]) => {
line(x1,y1,x2,y2);
return [x2,y2];
});
}
}
const s = new DotString(100, 3)
function setup() {
createCanvas(600, 600);
}
let tx, ty, t, cx = 0, cy = 0;
function randTarget() {
tx = Math.random() * 600;
ty = Math.random() * 600;
t = Math.floor(Math.random() * 12 + 6);
}
randTarget();
function draw() {
background(0);
if(t == 0) randTarget();
else t--;
cx += (tx - cx)/25;
cy += (ty - cy)/25;
s.move(cx, cy);
s.render();
}