xxxxxxxxxx
// Creative Coding for Beginners
// https://www.amazon.com/dp/B085RNLGKQ
var list_of_balls = [];
var total_balls = 20;
function setup() {
simple();
for (var i=0; i< total_balls; i++) {
list_of_balls.push(new Ball);
}
strokeWeight(1);
loop();
}
function draw() {
// blank animation frame
background(51);
// for every ball in list
for (ball of list_of_balls) {
ball.show();
ball.move();
}
// draw border
noFill(); stroke(0); rect(0, 0, width-1, height-1);
stroke(0, 0, 200, 100); rect(200, 100, 400, 400);
}
// blueprint for a Ball
class Ball {
constructor() {
this.x = 400;
this.y = 300;
this.x_speed = -3 + 10*random();
this.y_speed = -1 - 6*random();
this.gravity = 0.05;
}
show() {
stroke(220, 0, 0, 150);
var a = (abs(this.x_speed) + abs(this.y_speed))*10;
fill(220, 0, 0, a);
//fill(220, 0, 0, 50);
circle(this.x, this.y, 20);
}
move() {
this.x += this.x_speed;
this.y += this.y_speed;
// check if ball hits edge
if (this.x > 600) {
this.x_speed *= -0.7;
this.x = 599;
fill('lightgreen');
circle(this.x, this.y, 20);
}
if (this.x < 200) {
this.x_speed *= -0.7;
this.x = 201;
fill('lightgreen');
circle(this.x, this.y, 20);
}
if (this.y > 500) {
if (random() < 0.9) {
this.y_speed *= -0.9;
this.y = 499;
fill('yellow');
circle(this.x, this.y, 20);
} else {
// fire!
this.y_speed *= -2.0;
this.y = 499;
fill('rgb(255,0,172)');
circle(this.x, this.y, 20);
}
}
if (this.y < 100) {
this.y_speed *= -0.9;
this.y = 101;
fill('yellow');
circle(this.x, this.y, 20);
}
// check of ball hits other balls
for (ball of list_of_balls) {
if (ball != this) {
var d = (this.x-ball.x)**2 + (this.y-ball.y)**2;
if (d < 450) {
this.x_speed *= - Math.sign(this.x-ball.x);
this.y_speed *= - Math.sign(this.y-ball.y);
this.x += Math.sign(this.x-ball.x);
this.y += Math.sign(this.y-ball.y);
//
ball.x_speed *= Math.sign(this.x-ball.x);
ball.y_speed *= Math.sign(this.y-ball.y);
ball.x += Math.sign(this.x-ball.x);
ball.y += Math.sign(this.y-ball.y);
fill(220,0,0,50);
circle(this.x, this.y, 20);
}
}
}
this.y_speed += this.gravity;
}
}