Добавить атрибут к классу Bubble
, который гласит, было ли прикосновение к пузырю (this.hit
):
class Bubble {
constructor(x, y, r){
// [...]
this.hit = false;
}
// [...]
Установить цвет заливки в зависимости от состояния при рисовании пузыря:
class Bubble {
// [...]
display() {
// [...]
if (this.hit) {
fill(102, 102, 255);
} else {
noFill();
}
ellipse(this.x, this.y, this.r*2);
}
Изменение состояния при наведении курсора мыши на пузырь. При желании вы можете сбросить состояние, если мышь «покидает» пузырь:
class Bubble {
// [...]
coverColor() {
let d = dist( mouseX, mouseY, this.x, this.y);
if (d < this.r){
this.hit = true;
} else {
// this code would cancel the "hit" state, when the mouse leaves the bubble
// this.hit = false;
}
}
// [...]
См. Пример:
var bubbles = [];
function setup(){
createCanvas(600, 400);
for (let i = 0; i < 5; i++) {
let x = random(width);
let y = random(height);
let r = random(10, 50);
bubbles.push(new Bubble(x, y, r));
}
}
function draw(){
background(0);
for(let i = 0; i < bubbles.length; i++){
bubbles[i].move();
bubbles[i].display();
}
}
function mouseMoved(){
for(let i = 0; i < bubbles.length; i++){
bubbles[i].coverColor();
}
}
class Bubble {
constructor(x, y, r){
this.x = x;
this.y = y;
this.r = r;
this.hit = false;
}
coverColor() {
let d = dist( mouseX, mouseY, this.x, this.y);
if (d < this.r){
this.hit = true;
} else {
// this code would cancel the "hit" state, when the mouse leaves the bubble
// this.hit = false;
}
}
display() {
stroke(0, 191, 255);
strokeWeight(2);
if (this.hit) {
fill(102, 102, 255);
} else {
noFill();
}
ellipse(this.x, this.y, this.r*2);
}
move() {
this.x = this.x + random(1, -1);
this.y = this.y + random(1, -1);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/p5.js"></script>