I’ve got a class defined for a button. I define this button globally as b1 and in setup define the size and values. Then in draw I have b1.update() and b1.display() and if(b1.press()) {functionon = !functionon}; where functionon essentially carries out what I want the button to do when pressed.
It works sometimes, but sometimes when I click the button - the colour doesn’t change nor does the function work - what could be the reason?
Code of my class below:
class Buttons {
int rectX, rectY;
int circleX, circleY;
int rectSize;
int circleSize;
color rectColor, circleColor;
color oC;
color rectHighlight, circleHighlight;
boolean rectOver;
boolean circleOver;
boolean on = true;
int shape;
Buttons (int shaper, int x, int y, int size, color cl, int hl) {
shape = shaper;
if (shape == 1){
rectX = x;
rectY = y;
rectSize = size;
rectColor = cl;
rectHighlight = hl;
}else if (shape == 0){
circleX = x;
circleY = y;
circleSize = size;
circleColor = cl;
circleHighlight = hl;
}
oC = cl;
}
void update() {
if ( overCircle(circleX, circleY, circleSize) ) {
circleOver = true;
rectOver = false;
} else if ( overRect(rectX, rectY, rectSize, rectSize) ) {
rectOver = true;
circleOver = false;
} else {
circleOver = rectOver = false;
}
}
boolean press(){
if(shape ==1){
if (mousePressed & rectOver){
on = !on;
if (on == false){
rectColor = rectHighlight;
} else{
rectColor = oC;
}
return true;
} else{
return false;
}
}else{
if (mousePressed & circleOver){
on = !on;
if (on == false){
circleColor = circleHighlight;
} else{
circleColor = oC;
}
return true;
} else{
return false;
}
}
}
boolean overRect(int x, int y, int width, int height) {
if (mouseX >= x && mouseX <= x+width &&
mouseY >= y && mouseY <= y+height) {
return true;
} else {
return false;
}
}
boolean overCircle(int x, int y, int diameter) {
float disX = x - mouseX;
float disY = y - mouseY;
if (sqrt(sq(disX) + sq(disY)) < diameter/2 ) {
return true;
} else {
return false;
}
}
void display() {
if (rectOver) {
fill(rectHighlight);
} else {
fill(rectColor);
}
stroke(255);
rect(rectX, rectY, rectSize, rectSize);
if (circleOver) {
if(on){
fill(circleHighlight);
}else{
fill(oC);
}
} else {
fill(circleColor);
}
stroke(0);
ellipse(circleX, circleY, circleSize, circleSize);
}
}