xxxxxxxxxx
61
class DotString {
constructor(n, r, ix=0, iy=0) {
this.xs = [[ix, iy]];
while(this.xs.length < n) {
this.xs.push([ix,iy]);
}
this.r = r;
}
move(x,y) {
this.xs[0][0] = x;
this.xs[0][1] = y;
for(let i = 0; i < this.xs.length - 1; i++) {
const dx = this.xs[i][0] - this.xs[i+1][0];
const dy = this.xs[i][1] - this.xs[i+1][1];
const d2 = dx*dx + dy*dy;
if(d2 > this.r * this.r) {
const a = Math.atan2(dy, dx);
this.xs[i+1][0] = -Math.cos(a) * this.r + this.xs[i][0];
this.xs[i+1][1] = -Math.sin(a) * this.r + this.xs[i][1];
}
}
}
render() {
stroke(255);
let first = true;
let ix, iy;
for(const [x,y] of this.xs) {
if(first) {
ix = x;
iy = y;
first = false;
} else {
line(ix, iy, x, y);
ix = x;
iy = y;
}
}
}
}
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();
}