xxxxxxxxxx
61
let circles = []
function setup() {
createCanvas(400, 400);
for (let i = 0; i < 10; i++) {
circles.push(new Circle(random(width),random(height),10))
}
}
function draw() {
background(0);
circles[0].x = mouseX
circles[0].y = mouseY
for (let circle of circles) {
circle.update()
for(let other of circles) {
let d = dist(circle.x,circle.y,other.x,other.y)
let radii_sum = circle.colr + other.colr
if (circle !== other && d < radii_sum) {
let dx = other.x - circle.x
let dy = other.y - circle.y
let unit_x = dx / d
let unit_y = dy / d
other.x = circle.x + radii_sum * unit_x
other.y = circle.y + radii_sum * unit_y
}
}
}
}
class Circle {
constructor(x,y,r) {
this.x = x
this.y = y
this.r = r //radius of the visual circle
this.colr = this.r + 5 //radius of the collison
this.rot = 0
}
move() {
this.rot = atan2(circles[0].y - this.y,circles[0].x - this.x)
this.x += cos(this.rot) * 2 // mutiplying changes speed
this.y += sin(this.rot) * 2
}
show() {
noStroke()
fill(255)
ellipse(this.x,this.y,this.r*2)
}
update() {
this.move()
this.show()
}
}