Array of objects weirdness
in
Programming Questions
•
1 year ago
I'm trying to create an array of interactive button objects. So far I created an array of the class and it works almost perfectly, except the buttons' behaviour. When they're clicked, they're supposed to change their color to give a feedback that a button is pressed. Instead, different buttons change their color instead of the one clicked. I cannot make sense of it... Also, I wonder how can I create a for loop to iterate the x and y variables for the position of button, rather than having to enter them manually.
int col=50;
Button[] button=new Button[8];
void setup() {
size(500, 500);
//for (int i=0;i<button.length;i++) {
button[0]=new Button(col, 50);
button[1]=new Button(col, 120 );
button[2]=new Button(col, 190);
button[3]=new Button(col, 260 );
button[4]=new Button(col+70, 50 );
button[5]=new Button(col+70, 120 );
button[6]=new Button(col+70, 190 );
button[7]=new Button(col+70, 260 );
}
void draw() {
background(0);
for (int i=0;i<button.length;i++) {
button[i].display();
button[i].press();
}
smooth();
}
//and the class
int s=60;
int r=8;
int c=200;
class Button{
int x,y;
Button(int tempx,int tempy){
x=tempx;
y=tempy;
}
void display(){
fill(c);
stroke(75);
strokeWeight(4);
rect(x,y,s,s,r,r,r,r);
}
boolean over(){
if(mouseX>=x && mouseX<=(x+s) && mouseY>=y && mouseY<=(y+s)){
return true;
} else {
return false;
}
}
void press(){
if(over() && mousePressed){
c=100;
} else {
c=200;
}
}
}
1