Falling rope

Spring mass system

Log in to post a comment.

Canvas.setpenopacity(-0.02);

const t = new Turtle();

const M = 1;
const G = 10;
const N = 50;
const L = 300;
const K = 0.1;
const A = 0.0001;
const dt = 0.005;
const V = 1;

const m = M / N;
const len = L / N;

let x = [];
let y = [];
let vx = [];
let vy = [];

[x[0], y[0]] = [0, -100];
[x[N - 1], y[N - 1]] = [0, -100];

[vx[0], vy[0]] = [0, 0];
[vx[N - 1], vy[N - 1]] = [0, 0];

for (let i = 1; i < N - 1; i++) {
    x[i] = (N/2 - Math.min(i, N - 1 - i)) / N * 10
    y[i] = -100 + (L/2) / Math.floor(N/2) * Math.min(i, N - 1 - i);

    vx[i] = 0;
    vy[i] = 0;
}

function walk(frame) {
    new_x = [];
    new_y = [];
    
    [new_x[0], new_y[0]] = [Math.max(-100, x[0] - V * dt * (0.5 + Math.random())), y[0]];
    [new_x[N - 1], new_y[N - 1]] = [Math.min(100, x[N - 1] + V * dt * (0.5 + Math.random())), y[N - 1]];
    
    for (let i = 1; i < N - 1; i++) {
        let Fg = m * G;
        
        let phi = Math.atan2(vy[i], vx[i])
        
        let Fr_x = -A * vx[i]**2 * Math.cos(phi);
        let Fr_y = -A * vy[i]**2 * Math.sin(phi);
        
        let dx1 = x[i - 1] - x[i], dy1 = y[i - 1] - y[i];
        let dx2 = x[i + 1] - x[i], dy2 = y[i + 1] - y[i];
        
        let d1 = Math.sqrt(dx1**2 + dy1**2), phi1 = Math.atan2(dy1, dx1);
        let d2 = Math.sqrt(dx2**2 + dy2**2), phi2 = Math.atan2(dy2, dx2);
        
        let F1 = K * (d1 - len)**2;
        let F2 = K * (d2 - len)**2;
        
        let F1x = F1 * Math.cos(phi1), F1y = F1 * Math.sin(phi1);
        let F2x = F2 * Math.cos(phi2), F2y = F2 * Math.sin(phi2);
        
        if (d1 < len) {
            F1x = -F1x;
            F1y = -F1y;
        }

        if (d2 < len) {
            F2x = -F2x;
            F2y = -F2y;
        }
        
        let Fx = F1x + F2x + Fr_x;
        let Fy = F1y + F2y + Fr_y + Fg;
        
        vx[i] += (Fx / m) * dt;
        vy[i] += (Fy / m) * dt;
        
        new_x[i] = x[i] + vx[i] * dt;
        new_y[i] = y[i] + vy[i] * dt;
    }
    
    for (let i = 0; i < N; i++) {
        [x[i], y[i]] = [new_x[i], new_y[i]];
    }
    
    //if (true) {
    if (frame % 2 == 0) {
    //if (frame <= 1000) {
        t.jump(x[0], -100 + (y[0] + 100) * 0.75);
        
        for (let i = 1; i < N; i++) {
            t.goto(x[i], -100 + (y[i] + 100) * 0.75);
        }
    }
    
    return frame < 20000;
}