Turtle Star

Turtles chasing turtles.

Log in to post a comment.

class Vector2d {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }

    scale(n) {
        return new Vector2d(this.x * n, this.y * n);
    }

    add(other) {
        return new Vector2d(this.x + other.x, this.y + other.y);
    }

    subtract(other) {
        return new Vector2d(this.x - other.x, this.y - other.y);
    }

    toArray() {
        return [this.x, this.y];
    }
}

// Parameters
Canvas.setpenopacity(1);
const numSteps = 720;
const numTurtles = 240;
const initialRadius = 120;
const moveFraction = 0.01;
const targetMultiplier = 6;

const turtles = [...Array(numTurtles)].map(n => new Turtle());
for (var i = 0; i < numTurtles; i++) {
    let turtle = turtles[i];
    let theta = 2 * i * Math.PI / numTurtles;

    turtle.penup();
    turtle.goto(Math.cos(theta) * initialRadius, Math.sin(theta) * initialRadius);
    turtle.pendown();
}

function step(n) {
    let newPositions = [];

    for (var i = 0; i < numTurtles; i++) {
        let movingTurtle = turtles[i];
        let targetTurtle = turtles[(targetMultiplier * i) % numTurtles];
        let movingVector = new Vector2d(movingTurtle.x(), movingTurtle.y());
        let targetVector = new Vector2d(targetTurtle.x(), targetTurtle.y());
        let newVector = movingVector.add(targetVector.subtract(movingVector).scale(moveFraction));
        newPositions.push(newVector.toArray());
    }

    for (var i = 0; i < numTurtles; i++) {
        turtles[i].goto(newPositions[i]);
    }
}

function walk(i) {
    step(i);
    return i < numSteps;
}