/* built with Studio Sketchpad:
* https://sketchpad.cc
*
* observe the evolution of this sketch:
* https://p5js.sketchpad.cc/sp/pad/view/ro.8yUQ4vfyGEx/rev.1549
*
* authors:
* WolfeSVK
* Sketchpad Admin
* license (unless otherwise specified):
* creative commons attribution-share alike 3.0 license.
* https://creativecommons.org/licenses/by-sa/3.0/
*/
var pendulums;
var count
var ballSize;
var mass = 1;
var time = 0.1;
var grav = 9.8;
var anchor;
//var col;
function setup() {
createCanvas(600, 400);
pendulums = [];
count = random(10,40);
col = round(random(500-5*count));
var lng = random(50,80);
var ang = random(0*PI/180,180*PI/180);
ballSize = (height - lng)/count;
anchor = createVector(width / 2, 15);
for (var i=0; i<count;i++){
pos = createVector(anchor.x+cos(ang)*lng, anchor.y+sin(ang)*lng);
pendulums.push(new Ball(anchor.x, anchor.y, pos.x, pos.y, col+i*5));
lng+=ballSize;
}
}
function draw() {
background(100);
for (var i=pendulums.length-1;i>=0;i--){
pendulums[i].update();
pendulums[i].paint();
}
}
function Ball(anchX, anchY, ballX, ballY, col) {
this.col = col;
this.anchorPos = createVector(anchX, anchY);
this.ballPos = createVector(ballX, ballY);
this.ball = p5.Vector.sub(this.ballPos, this.anchorPos);
this.length = this.anchorPos.dist(this.ballPos);
this.angle = atan2(this.ball.y, this.ball.x);
this.angleVel = 0;
}
Ball.prototype.update = function() {
this.ball = p5.Vector.sub(this.ballPos, this.anchorPos);
this.angleAcc = -grav / this.length * sin(this.angle);
this.angleVel += this.angleAcc * time;
this.angle += this.angleVel;
this.angle += HALF_PI; // set angle 0 to bottom
this.ballPos.x = cos(this.angle) * this.length + this.anchorPos.x;
this.ballPos.y = sin(this.angle) * this.length + this.anchorPos.y;
this.angle -= HALF_PI; // restore
this.ball = p5.Vector.sub(this.ballPos, this.anchorPos);
this.col++;
if (this.col > 499) this.col = 0;
}
Ball.prototype.paint = function() {
push();
colorMode(HSB, 500, 100, 100);
stroke(this.col, 100, 40);
fill(this.col, 100, 40);
line(this.anchorPos.x, this.anchorPos.y, this.ballPos.x, this.ballPos.y);
ellipse(this.anchorPos.x, this.anchorPos.y, 5, 5);
fill(this.col, 100, 100);
ellipse(this.ballPos.x, this.ballPos.y, ballSize, ballSize);
pop();
}
function keyPressed(){
setup();
}