xxxxxxxxxx
115
// Daniel Shiffman
// https://thecodingtrain.com/CodingChallenges/093-double-pendulum.html
// https://youtu.be/uWzPe_S-RVE
let r1 = 75;
let r2 = 75;
let m1 = 10;
let m2 = 10
let a1 = 0;
let a2 = 0;
let a1_v = 0;
let a2_v = 0;
let g = 0.25;
let cx, cy;
let buffer;
let timesteps = 1000;
let init_variance = 0.001
let x2_past = -1;
let y2_past = -1;
function setup() {
createCanvas(600, 350);
//Issue with wrong rendering on a retina Mac. See issue: https://github.com/CodingTrain/website/issues/574
randomSeed(millis()*10000);
let eps = (random()-0.5)*init_variance;
pixelDensity(1);
a1 = PI;
a2 = PI + eps;
cx = width / 2;
cy = height / 2;
buffer = createGraphics(width, height);
buffer.background(250);
buffer.translate(cx, cy);
}
function draw() {
background(250);
imageMode(CORNER);
image(buffer, 0, 0, width, height);
let num1;
let num2;
let num3;
let num4;
let den;
let a1_a;
let a2_a;
let x1;
let y1;
let x2;
let y2;
for(let t=0; t < timesteps; t++) {
num1 = -g * (2 * m1 + m2) * sin(a1);
num2 = -m2 * g * sin(a1 - 2 * a2);
num3 = -2 * sin(a1 - a2) * m2;
num4 = a2_v * a2_v * r2 + a1_v * a1_v * r1 * cos(a1 - a2);
den = r1 * (2 * m1 + m2 - m2 * cos(2 * a1 - 2 * a2));
a1_a = (num1 + num2 + num3 * num4) / den;
a1_a /= timesteps;
num1 = 2 * sin(a1 - a2);
num2 = (a1_v * a1_v * r1 * (m1 + m2));
num3 = g * (m1 + m2) * cos(a1);
num4 = a2_v * a2_v * r2 * m2 * cos(a1 - a2);
den = r2 * (2 * m1 + m2 - m2 * cos(2 * a1 - 2 * a2));
a2_a = (num1 * (num2 + num3 + num4)) / den;
a2_a /= timesteps;
x1 = r1 * sin(a1);
y1 = r1 * cos(a1);
x2 = x1 + r2 * sin(a2);
y2 = y1 + r2 * cos(a2);
a1_v += a1_a;
a2_v += a2_a;
a1 += a1_v/timesteps;
a2 += a2_v/timesteps;
}
translate(cx, cy);
stroke(0);
strokeWeight(0.1);
strokeWeight(1);
line(0, 0, x1, y1);
fill(0);
ellipse(x1, y1, m1*0.2, m1*0.2);
line(x1, y1, x2, y2);
fill(0);
ellipse(x2, y2, m2*0.2, m2*0.2);
buffer.stroke(0);
if (frameCount > 1) {
stroke(0, 100)
strokeWeight(0.5);
buffer.line(x2_past, y2_past, x2, y2);
}
x2_past = x2;
y2_past = y2;
}