Simple circle packing. Drag the circles around and press the space bar to reset random sizes for each circle. Link to source files.
let inertia = 0.9;
let k;
let circles = [];
let pressed = [];
let rad = [];
let Ccolor = [];
let damping = 1;
let numcircles = 60;
let xOffset;
let yOffset;
function setup() {
createCanvas(800,800);
frameRate(30);
k = random(1.0) * 0.02 + 0.02;
for(var i = 0; i < numcircles; i++){
circles[i] = createVector(random(width)-width/2,random(height)-height/2);
pressed[i] = 0;
rad[i] = int(random(120)+10);
Ccolor[i] = color(random(255),random(255),random(255));
}
}
function draw() {
background(0);
damping = 1;
for(let c = 0; c < 10; c++){
limit = numcircles;
for(let i = 0; i < numcircles; i++){
for(let j = 0; j < numcircles; j++){
let distx = circles[j].x - circles[i].x;
let disty = circles[j].y - circles[i].y;
let rmax = rad[i]/2 + rad[j]/2;
let dst = (distx * distx) + (disty * disty);
if (dst < ((rmax * rmax) - .01) ){
let vectorx = distx;
let vectory = disty;
///normalize
let d = dist(circles[i].x, circles[i].y, circles[j].x, circles[j].y);
if(d == 0){
vectorx = 0;
vectory = 0;
}else{
vectorx = vectorx/d;
vectory = vectory/d;
}
vectorx = vectorx * (rmax - d) * .5;
vectory = vectory * (rmax - d) * .5;
//trace(rmax);
if((pressed[j] == 0)){
circles[j].x += vectorx;
circles[j].y += vectory;
}
if((pressed[i] == 0)){
circles[i].x -= vectorx;
circles[i].y -= vectory;
}
}
}
}
damping = damping * .05;
i = 0;
for(let i = 0; i < numcircles; i++){
vectorx = circles[i].x;
vectory = circles[i].y;
vectorx = vectorx * damping;
vectory = vectory * damping;
if((pressed[i] == 0)){
circles[i].x -= vectorx;
circles[i].y -= vectory;
}
}
}
for(var i = 0; i < numcircles; i++){
noStroke();
fill(Ccolor[i]);
ellipse(circles[i].x+width/2,circles[i].y+height/2, rad[i],rad[i]);
}
}
function mousePressed() {
for(let i = 0; i < numcircles; i++){
let d = dist(circles[i].x+width/2, circles[i].y+height/2, mouseX, mouseY);
if(d < rad[i]/2){
pressed[i] = 1;
xOffset = mouseX-circles[i].x;
yOffset = mouseY-circles[i].y;
}else{
pressed[i] = 0;
}
}
}
function mouseDragged(){
for(let i = 0; i < numcircles; i++){
if(pressed[i] == 1){
circles[i].x = mouseX-xOffset;
circles[i].y = mouseY-yOffset;
}
}
}
function mouseReleased() {
for(let i = 0; i < numcircles; i++){
pressed[i] = 0;
}
}
function keyPressed() {
if (key == ' ') {
for(var i = 0; i < numcircles; i++){
rad[i] = int(random(120)+10);
}
}
}