xxxxxxxxxx
143
var t;
let numBalls = 13;
let spring = 0.05;
let gravity = 0;
let friction = -0.9;
let balls = [];
function setup() {
createCanvas(400, 400);
for (let i = 0; i < numBalls; i++) {
balls[i] = new Ball(random(width), random(height), random(30, 80), i, balls);
}
t = 0;
}
function draw() {
background(0);
for (let i = 0; i < balls.length; i++) {
balls[i].collide();
balls[i].move();
balls[i].display();
t = t + 0.01;
}
}
function mousePressed() {
//for loop
for (let i = 0; i < numBalls; i++) {
//array that contains objects + function to make it move when clicked
balls[i].over(mouseX, mouseY);
}
}
class Ball {
constructor(xin, yin, din, idin, oin) {
this.x = xin;
this.y = yin;
this.vx = 0;
this.vy = 0;
this.diameter = din;
this.id = idin;
this.others = oin;
this.c = color(255, 204, 0, 204);
}
collide() {
for (let i = this.id + 1; i < numBalls; i++) {
//onsole.log(others[i]);
let dx = this.others[i].x - this.x;
let dy = this.others[i].y - this.y;
let distance = sqrt(dx * dx + dy * dy);
let minDist = this.others[i].diameter / 2 +
this.diameter / 2;
// console.log(distance);
//console.log(minDist);
if (distance < minDist) {
//console.log("2");
let angle = atan2(dy, dx);
let targetX = this.x + cos(angle) * minDist;
let targetY = this.y + sin(angle) * minDist;
let ax = (targetX - this.others[i].x) * spring;
let ay = (targetY - this.others[i].y) * spring;
this.vx -= ax;
this.vy -= ay;
this.others[i].vx += ax;
this.others[i].vy += ay;
}
}
}
move() {
this.vy += gravity;
this.x += this.vx;
this.y += this.vy;
if (this.x + this.diameter / 2 > width) {
this.x = width - this.diameter / 2;
this.vx *= friction;
} else if (this.x - this.diameter / 2 < 0) {
this.x = this.diameter / 2;
this.vx *= friction;
}
if (this.y + this.diameter / 2 > height) {
this.y = height - this.diameter / 2;
this.vy *= friction;
} else if (this.y - this.diameter / 2 < 0) {
this.y = this.diameter / 2;
this.vy *= friction;
}
}
over(mx, my) {
//find the distance between the
//mouse and the x and y position of the object
let distance = dist(mx, my, this.x, this.y);
//if its less than the width change the color and speed
//note that rectMode(CENTER); is enabled here
if (distance < this.diameter / 2) {
//change the fill color to greenish
this.c = color(255,0,0);
//change the speed
this.speed = this.speed + 9;
} else {
//change back to orginal color
this.c = color(255, 204, 0, 204);
}
// //if the speed goes over a certain amount, slow it down
// if (this.speed > 20) {
// this.speed = 7;
// }
}
display() {
noStroke();
fill(this.c);
ellipse(this.x, this.y, this.diameter, this.diameter);
circle(this.x, this.y, this.diameter, this.diameter);
}
}