xxxxxxxxxx
62
// Mouse Interaction with Objects
// Code! Programming with p5.js
// The Coding Train / Daniel Shiffman
// https://thecodingtrain.com/beginners/p5js/7.4-mouse-interaction.html
// https://youtu.be/TaN5At5RWH8
// https://editor.p5js.org/codingtrain/sketches/lE4ypFpI
let bubbles = [];
function setup() {
createCanvas(600, 400);
for (let i = 0; i < 10; i++) {
let x = random(width);
let y = random(height);
let w = random(20, 60);
let b = new Bubble(x, y, w);
bubbles.push(b);
}
}
function mousePressed() {
for (let i = 0; i < bubbles.length; i++) {
bubbles[i].clicked(mouseX, mouseY);
}
}
function draw() {
background(0);
for (let i = 0; i < bubbles.length; i++) {
bubbles[i].move();
bubbles[i].show();
}
}
class Bubble {
constructor(x, y, w) {
this.x = x;
this.y = y;
this.w = w;
this.brightness = 0;
}
clicked(px, py) {
let d = dist(px, py, this.x, this.y);
if (d < this.w) {
this.brightness = 125;
}
}
move() {
this.x = this.x + random(-2, 2);
this.y = this.y + random(-2, 2);
}
show() {
stroke(255);
strokeWeight(4);
fill(this.brightness);
rect(this.x, this.y, this.w, this.w);
}
}