xxxxxxxxxx
78
// Spring Forces (Simple Spring)
// The Coding Train / Daniel Shiffman
// https://thecodingtrain.com/CodingChallenges/160-spring-forces.html
// https://youtu.be/Rr-5HiXquhw
// Simple Spring: https://editor.p5js.org/codingtrain/sketches/dcd6-2mWa
// Spring Vector: https://editor.p5js.org/codingtrain/sketches/_A2pm_SSg
// Spring OOP: https://editor.p5js.org/codingtrain/sketches/9BAoEn4Po
// Soft Spring: https://editor.p5js.org/codingtrain/sketches/S5dY7qjxP
let angle;
let angleV = 0;
let angleA = 0;
let bob;
let len;
let origin;
let gravity = 1;
let y = 250;
let velocity = 0;
let restLength = 200;
let k = 0.005;
let kSlider;
function setup() {
createCanvas(600, 400);
kSlider = createSlider(0, 0.01, k, 0);
createSpan(`K (0-0.01)`);
origin = createVector(300, 0);
angle = PI / 4;
bob = createVector(0, y);
//location.href = "https://editor.p5js.org/codingtrain/sketches/SN-39sHAC";
}
function draw() {
background(112, 50, 126);
k = kSlider.value();
stroke(255);
strokeWeight(8);
line(origin.x, origin.y, bob.x, bob.y);
noStroke();
fill(45, 197, 244);
circle(bob.x, bob.y, 64);
// Wrong! len = y = bob.y;
len = dist(bob.x, bob.y, origin.x, origin.y);
y = bob.y;
/* Pendulum stuff */ {
let force = gravity * sin(angle);
angleA = (-1 * force) / len;
angleV += angleA;
angle += angleV;
// angleV *= 0.99;
bob.x = len * sin(angle) + origin.x;
bob.y = len * cos(angle) + origin.y;
}
/* Spring stuff */ {
let x = y - restLength;
let springForce = -k * x;
// F = A
velocity += springForce;
bob.y += velocity;
velocity *= 0.99;
}
}