xxxxxxxxxx
126
// Smooth bubble dance
var bubbles = []
var margin = 30 // Pixel border around canvas
var bubbleCount = 50
var frame = 0 // The current draw frame
var smoothness = 300 // Bubble velocity will not
// change after more than this
// many frames
var speed = 0.5
var colors = {}
class Bubble {
constructor(x, y, r) {
this.x = x
this.y = y
this.r = r
// Has the mouse clicked on the bubble?
this.selected = false
// Is this bubble within another bubble?
this.intersected = false
// This bubbles independant flow speed
this.flowX = 0
this.flowY = 0
// The draw frame at which this current bubble
// will change course
this.changeAt = floor(random(smoothness))
}
// Change the course of this bubble
change() {
this.flowX = random(-speed, speed)
this.flowY = random(-speed, speed)
}
// The bubbles motion between each draw frame
move(w, h) {
// The width and height of the canvas will
// be reduced by the margins
w -= margin * 2
h -= margin * 2
// Bubble flow will wrap around the canvas
// instead of dissappear it
this.x = (w + this.x + this.flowX) % w
this.y = (h + this.y + this.flowY) % h
}
mouseInBubble(x, y) {
// s%^@&# margin
var d = dist(this.x + margin, this.y + margin, x, y)
return (d < this.r)
}
bubbleInBubble(b2) {
var d = dist(this.x, this.y, b2.x, b2.y)
return (d < (this.r + b2.r) )
}
}
function mousePressed() {
// Just update which bubble is clicked on
// to let draw() know about it
for(var b of bubbles) {
b.selected = b.mouseInBubble(mouseX, mouseY)
}
}
// Just update which bubble clashes with another
// to let draw() know about it
function updateIntersections() {
for(var b of bubbles)
b.intersected = false
for(var i = 0; i < bubbles.length - 1; i++) {
for(var j = i+1; j < bubbles.length; j++) {
if(bubbles[i].bubbleInBubble(bubbles[j])) {
bubbles[i].intersected = true
bubbles[j].intersected = true
}
}
}
}
function setup() {
createCanvas(600, 500);
colors = {
stroke: color(255),
background: color(255, 127, 127),
intersect: color(255, 255, 0, 100),
click: color(0, 255, 0, 100)
}
stroke(colors.stroke)
while(bubbleCount-- > 0) {
bubbles.push(new Bubble(
random(width - margin),
random(height - margin),
random(margin/4, margin)
))
}
}
function draw() {
background(colors.background);
for(var b of bubbles) {
// Handle whether or not to color the bubble
// based on who it is
if(b.selected)
fill(colors.click)
else if(b.intersected)
fill(colors.intersect)
else
noFill()
// s%^@&# margin
circle(margin + b.x, margin + b.y, 2 * b.r)
// This bubbles velocity will change
// at a frame number stored in the bubble object
if(frame % b.changeAt === 0)
b.change()
// Only check for bubble clashes every few
// frames or so. There's a bit of a coloring
// delay as a cost
if(frame % 30 === 0)
updateIntersections()
b.move(width, height)
}
frame++
}