From 7757f565bf0f7694c6de57a2795117521c92e5a7 Mon Sep 17 00:00:00 2001 From: Nat Lasseter Date: Wed, 28 Jun 2017 21:11:50 +0100 Subject: Some bouncy lines --- particle.js | 20 ++++++++++++++++++-- sketch.js | 18 ++++++++++++++---- 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/particle.js b/particle.js index c62dd47..b6b116c 100644 --- a/particle.js +++ b/particle.js @@ -30,7 +30,23 @@ function Particle(x, y, m, c) { point(this.pos.x, this.pos.y); } - this.gone = function() { - return this.pos.y >= hei; + this.reflect = function(surface_vector, elastic_coeff) { + var normal = surface_vector + .copy() + .normalize() + .rotate(PI/2); + this.vel = this.vel.sub(p5.Vector.mult(normal, 2 * this.vel.dot(normal))).mult(elastic_coeff); + } + + this.online = function(x1, y1, x2, y2) { + var dist = function(x1, y1, x2, y2) { + return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)); + }; + + return Math.abs( + dist(x1, y1, this.pos.x, this.pos.y) + + dist(this.pos.x, this.pos.y, x2, y2) - + dist(x1, y1, x2, y2) + ) < 1; } } diff --git a/sketch.js b/sketch.js index 2c6b9d3..ce3d1d1 100644 --- a/sketch.js +++ b/sketch.js @@ -13,6 +13,11 @@ function setup() { function draw() { background(0); + stroke(255); + strokeWeight(4); + line(0, 0.75*hei, 0.25*wid, hei); + line(0.75*wid, hei, wid, 0.75*hei); + for(var i = ps.length - 1; i >= 0; i--) { ps[i].applyForce(gravity); ps[i].applyDrag(air_resistance); @@ -22,17 +27,22 @@ function draw() { strokeWeight(ps[i].mass); ps[i].show(); - if (ps[i].gone()) { - ps.splice(i, 1); + if (ps[i].online(0, 0.75*hei, 0.25*wid, hei)) { + ps[i].reflect(createVector(0.25*wid, 0.25*hei), 5); + } else if (ps[i].online(0.75*wid, hei, wid, 0.75*hei)) { + ps[i].reflect(createVector(0.25*wid, -0.25*hei), 5); } + + if (ps[i].pos.y >= hei) + ps.splice(i, 1); } if (mouseIsPressed) { var p = new Particle( - mouseX, mouseY, random(2, 8), + mouseX, mouseY, random(2, 10), color(random(0, 360), random(90, 100), random(50, 100)) ); - p.applyForce(createVector(random(-200, 200), random(-400, 0))); + p.applyForce(createVector(random(-250, 250), random(-500, 0))); ps.push(p); } } -- cgit v1.2.1