xxxxxxxxxx
// hit key "s" to make them all smile...
int numBalls = 12;
float spring = 0.05;
float gravity = 0.03;
float friction = -0.9;
Ball[] balls = new Ball[numBalls];
void setup() {
size(640, 360);
for (int i = 0; i < numBalls; i++) {
balls[i] = new Ball(random(width), random(height), random(30, 70), i, balls);
}
noStroke();
fill(255, 204);
}
void draw() {
background(0);
for (Ball ball : balls) {
ball.collide();
ball.move();
ball.display();
}
}
class Ball {
float x, y;
float diameter;
float vx = 0;
float vy = 0;
int id;
Ball[] others;
Ball(float xin, float yin, float din, int idin, Ball[] oin) {
x = xin;
y = yin;
diameter = din;
id = idin;
others = oin;
}
void collide() {
for (int i = id + 1; i < numBalls; i++) {
float dx = others[i].x - x;
float dy = others[i].y - y;
float distance = sqrt(dx*dx + dy*dy);
float minDist = others[i].diameter/2 + diameter/2;
if (distance < minDist) {
float angle = atan2(dy, dx);
float targetX = x + cos(angle) * minDist;
float targetY = y + sin(angle) * minDist;
float ax = (targetX - others[i].x) * spring;
float ay = (targetY - others[i].y) * spring;
vx -= ax;
vy -= ay;
others[i].vx += ax;
others[i].vy += ay;
}
}
}
void move() {
vy += gravity;
x += vx;
y += vy;
if (x + diameter/2 > width) {
x = width - diameter/2;
vx *= friction;
}
else if (x - diameter/2 < 0) {
x = diameter/2;
vx *= friction;
}
if (y + diameter/2 > height) {
y = height - diameter/2;
vy *= friction;
}
else if (y - diameter/2 < 0) {
y = diameter/2;
vy *= friction;
}
}
void display() {
fill(0, 0, 255);
ellipse(x, y, diameter, diameter);
fill(255);
ellipse(x-10, y-5, 20, 20);
ellipse(x+10, y-5, 20, 20);
fill(0);
ellipse(x-10, y-5, 10, 10);
ellipse(x+10, y-5, 10, 10);
fill(255, 0, 0);
arc(x, y+6, 40, 30, 0, 3.14);
}
}
void keyPressed() {
if (key == 's') {
fill(0, 0, 255);
ellipse(320, 230, 200, 150);
fill(255);
ellipse(300, 200, 50, 50);
ellipse(350, 200, 50, 50);
fill(0);
ellipse(300, 200, 20, 20);
ellipse(350, 200, 20, 20);
fill(255, 0, 0);
arc(320, -230, 150, 150, 0, PI);
}
}