Advertisement
here2share

$ circlepack.js

Sep 18th, 2022
592
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let c,
  2.     bg,
  3.     shape_array = [],
  4.     kills = 0;
  5.  
  6. function setup() {
  7.     createCanvas(1280, 1280);
  8.     c = "#f3e5dc";
  9.     bg = color("#142b42");
  10.     background(bg);
  11. }
  12.  
  13. class Shape {
  14.     constructor(x, y, radius) {
  15.         this.x = x;
  16.         this.y = y;
  17.         this.r = radius;
  18.     }
  19.  
  20.     draw() {
  21.         stroke(c);
  22.         strokeWeight(1);
  23.         noFill();
  24.         circle(this.x, this.y, this.r * 2);
  25.     }
  26.  
  27.     grow() {
  28.         this.r++;
  29.         this.draw();
  30.     }
  31. }
  32.  
  33. function detectEdgeCollision(shape) {
  34.     if (
  35.         dist(shape.x, shape.y, 0, shape.y) <= shape.r ||
  36.         dist(shape.x, shape.y, width, shape.y) <= shape.r ||
  37.         dist(shape.x, shape.y, shape.x, 0) <= shape.r ||
  38.         dist(shape.x, shape.y, shape.x, height) <= shape.r
  39.     ) {
  40.         return true;
  41.     }
  42.     return false;
  43. }
  44.  
  45. function detectShapeCollision(shape, array) {
  46.     for (let i = 0; i < array.length; i++) {
  47.         let shape2 = array[i];
  48.         let distance = dist(shape.x, shape.y, shape2.x, shape2.y);
  49.         if (distance !== 0 && distance <= shape.r + shape2.r) {
  50.             if (shape.r === 1) {
  51.                 array.pop();
  52.                 kills++;
  53.             }
  54.             return true;
  55.         }
  56.     }
  57.     return false;
  58. }
  59.  
  60. function draw() {
  61.     background(bg); // Clear the background on every iteration!
  62.  
  63.     let shape = new Shape(random(0, width), random(0, height), 1);
  64.     shape_array.push(shape);
  65.     for (let s of shape_array) {
  66.         if (detectEdgeCollision(s)) {
  67.             s.draw();
  68.         } else if (detectShapeCollision(s, shape_array)) {
  69.             if (s.r > 1) {
  70.                 s.draw();
  71.             }
  72.         } else {
  73.             s.grow();
  74.         }
  75.     }
  76.  
  77.     if (kills > 10000) {
  78.         console.log("stopped");
  79.         noLoop();
  80.     }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement