xxxxxxxxxx
122
let randradius;
let linelist = [];
let maxradius;
let xoffset;
let maxdx;
let maxdy;
let bg;
//a function that checks a linelist for the line with most collisions, and return the color of that line
function getMostCollisions(linelist){
let maxcollisions = 0;
let maxcollisioncolor;
for(let i=0; i < linelist.length; i++){
if(linelist[i].numcollisions>maxcollisions){
maxcollisions = linelist[i].numcollisions;
maxcollisioncolor = linelist[i].color;
}
}
return maxcollisioncolor||bg;
}
function setup() {
createCanvas(500, 500);
bg = color(220,220,220)
xoffset = 30;
maxradius = 3;
maxdx = 3;
maxdy = 3;
for(let i=0; i<width/(xoffset+maxradius)-1; i++){
randradius = random(maxradius);
linelist.push(new BouncyLine(
random(maxdx),
random(maxdy),
randradius,
(i+1)*xoffset,
random(randradius,height-randradius),
));
}
}
//set background to line with most collisions
//check collisions for each combination of lines
function draw() {
bg = getMostCollisions(linelist)
background(bg);
for(let i=0; i < linelist.length; i++){
linelist[i].run();
}
for(let i=0; i < linelist.length-1; i++){
for(let j=i+1; j < linelist.length; j++){
linelist[i].checkCollision(linelist[j])
}
}
}
class BouncyLine{
constructor(dx, dy, radius, posX, posY){
this.color = color(random(255), random(255), random(255));
this.dx = dx;
this.dy = dy;
this.radius = radius;
this.posX = posX;
this.posY = posY;
this.initposX = posX;
this.initposY = posY;
this.numcollisions = 0;
this.pastlist = [];
}
//draw the current set of lines based on pastlist and current initposX&Y
draw(){
strokeWeight(this.radius*2);
for(let i=0; i<this.pastlist.length; i++){
stroke(this.pastlist[i][4])
line(this.pastlist[i][0],this.pastlist[i][1],this.pastlist[i][2],this.pastlist[i][3]);
}
stroke(this.color);
line(this.initposX, this.initposY, this.posX, this.posY);
}
//a method that updates the pastlist and sets initposX and Y to be the current posX and posY
updateList(){
this.pastlist.push([this.initposX, this.initposY, this.posX, this.posY, this.color]);
this.initposX = this.posX;
this.initposY = this.posY
}
update(){
this.posX += this.dx;
this.posY += this.dy;
if(this.posX > width-this.radius || this.posX<this.radius){
this.dx*=-1;
this.updateList();
}
if(this.posY > height-this.radius || this.posY<this.radius){
this.dy*=-1
this.updateList();
}
}
//method to draw the circle and update its position
run(){
this.draw();
this.update();
}
//a method to check if 2 line heads are touching using euclidean distance
//if they are, reverse dx dy, invert colors, and increment numcollisions for both
checkCollision(otherHead){
if(sqrt((otherHead.posX-this.posX)**2+(otherHead.posY-this.posY)**2)<(this.radius+otherHead.radius)){
this.dx*=-1;
this.dy*=-1;
this.updateList();
otherHead.updateList();
otherHead.dx*=-1;
otherHead.dy*=-1;
let otherColor = otherHead.color;
otherHead.color = this.color;
this.color = otherColor;
this.numcollisions +=1;
otherHead.numcollisions+=1;
}
}
}