I created a class on javascript using the p5.js package and I would like to know how I could modify the inner properties of a method with another method belonging to the same class.
So I basically created a class called bubble and those bubble(ellipse) move randomly in my canvas and bounce on the edge, this no problem. However I would like that, when I click on a bubble it transforms itself in a rectangle.
Please find the code after:
let bubbles = [];
// declare the Bubbles array at the top.
function setup() {
createCanvas(600, 400);
for (let i = 0; i < 5; i++) // will create i number of them.
{
let x = 10 + i / 20; // for the radisu of the ellipse
bubbles[i] = new Bubble(random(0, 600), random(0, 400), 40, i);
}
// to create the elements; specify the arguments there. to create new arguments, goes in the constructor.
// it is not mandatory to create the object here, you can also do it when the mouse is pressed=> see below
}
function mousePressed() {
for (let i = 0; i < bubbles.length; i++) {
bubbles[i].clicked(mouseX, mouseY);
}
}
function draw() {
background(0, 40);
for (let i = 0; i < bubbles.length; i++) { // i < bubbles.length , so when we create buble in setup they are all displayed .
bubbles[i].move();
bubbles[i].show();
bubbles[i].edge();
}
}
class Bubble {
constructor(x, y, r, col) {
this.x = x; // inside a class, "this" is a refercence to the current object
this.y = y; // those are the data used for the creation of the bubble.
this.r = r;
this.col = col; // color.
}
move() {
this.x = this.x + random(-1, 1);
this.y = this.y + random(-1, 1)
} // this would not work without the "this."
// move () declare a functionality, what it means for a bubble to move.
edge() { // create the bouncing function.
if (this.x < 0) {
this.x = this.x + random(20, 30)
};
if (this.x > width) {
this.x = this.x + random(-30, 20)
};
if (this.y < 0) {
this.y = this.y + random(20, 30)
};
if (this.y > height) {
this.y = this.y + random(-30, 20)
};
}
clicked(px, py) {
if (dist(this.x, this.y, px, py) < this.r) {
console.log('youclicked on bubble');
this.col = random(0, 255);
this.show() {
noStroke();
fill(this.col, 20, 100 + this.col);
rect(this.x, this.y, this.r * 2, this.r)
}
}
}
show() { //design attribute.
noStroke();
fill(this.col, 20, 100 + this.col);
ellipse(this.x, this.y, this.r * 2)
}
}
Basically in the clicked() method I would like that it changes the show() method. Ellipse => Rect when clicked on bubble.
Thanks for your help!
have a nice day