xxxxxxxxxx
89
// Spring Forces (Soft 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 particles = [];
let springs = [];
let spacing = 28;
let cols = 15, rows = 15;
let k = 0.5;
let xoff = 0;
let gravity;
function setup() {
createCanvas(windowWidth, windowHeight);
let startX = width / 2 - (spacing * (cols - 1)) / 2;
for (let j = 0; j < rows; j++) {
for (let i = 0; i < cols; i++) {
particles.push(
new Particle(1, startX + i * spacing, j * spacing, spacing * 0.5)
);
if (i > 0 && j > 0) {
let a = particles[i + j * cols];
let b = particles[i - 1 + j * cols];
let c = particles[i + (j - 1) * cols];
springs.push(new Spring(k, spacing, a, b));
springs.push(new Spring(k, spacing, a, c));
}
if (i == 0 && j > 0) {
let a = particles[i + j * cols];
let b = particles[i + (j - 1) * cols];
springs.push(new Spring(k, spacing, a, b));
}
if (i > 0 && j == 0) {
let a = particles[i + j * cols];
let b = particles[i - 1 + j * cols];
springs.push(new Spring(k, spacing, a, b));
}
}
}
for (let i = 0; i < cols; i++) particles[i].locked = true;
gravity = createVector(0, 0.1);
}
function draw() {
background(255);
fill(0);
noStroke();
textAlign(RIGHT, BOTTOM);
textSize(16);
text("framerate: " + nf(frameRate(), 1, 2), width - 5, height - 5);
stroke(0);
strokeWeight(2);
for (let i = springs.length - 1; i >= 0; i--) {
let s = springs[i];
s.show();
s.update();
if (s.a.position.y > height && s.b.position.y > height) {springs.splice(i, 1);}
if (mouseIsPressed) {
let x1 = s.a.position.x;
let y1 = s.a.position.y;
let x2 = s.b.position.x;
let y2 = s.b.position.y;
if (collideLineCircle(x1, y1, x2, y2, mouseX, mouseY, 10)) {
springs.splice(i, 1);
}
}
}
let wind = createVector(0.2*noise(xoff)-0.1,0);
for (let p of particles) {
p.applyForce(gravity);
let drag = p.velocity.copy();
let speed = drag.mag();
let dragMag = speed * speed * 0.02;
drag.normalize().mult(-1).mult(dragMag);
p.applyForce(drag);
p.applyForce(wind);
p.update();
}
xoff+=0.01;
}