Creating Buttons

edited September 2016 in Questions about Code

Ok I'm trying to make my own buttons here. The work, but the problem is with the below code the button switches off (Changes its color from white back to black) when I click anywhere in the window. I want it to only switch off if I click within each specific box. Any suggestions?

void setup() {

size(640, 360);

background(100); noStroke();

} int value1 = 0; int value2 = 0; int value3 = 0; int value4 = 0;

void draw() { fill(value1); rect(150, 50, 50, 50); fill(value2); rect(50, 210, 50, 50); fill(value3); rect(150, 210, 50, 50); fill(value4); rect(50, 50, 50, 50); }

void mouseReleased() { loop(); if (value1 == 0 & (mouseX > 149 && mouseX < 200 && mouseY > 49 && mouseY < 101)) { value1 = 255; } else { value1 = 0;

}
if (value2 == 0 & (mouseX > 49 && mouseX < 100 && mouseY > 209 && mouseY < 250)) { value2 = 255; } else { value2 = 0;

}
if (value3 == 0 & (mouseX > 149 && mouseX < 200 && mouseY > 209 && mouseY < 250)) { value3 = 255; } else { value3 = 0;

} if (value4 == 0 & (mouseX > 49 && mouseX < 100 && mouseY > 49 && mouseY < 101)) { value4 = 255; } else { value4 = 0;

} }

Tagged:

Answers

  • Answer ✓

    I improved the first 2 buttons in the code for you

    you need to check if it's inside button and then if button is 0 or not

    void setup() {
      size(640, 360);
    
      background(100); 
      noStroke();
    } 
    
    int value1 = 0; 
    int value2 = 0; 
    int value3 = 0; 
    int value4 = 0;
    
    void draw() { 
      fill(value1); 
      rect(150, 50, 50, 50); 
      fill(value2); 
      rect(50, 210, 50, 50); 
      fill(value3); 
      rect(150, 210, 50, 50); 
      fill(value4); 
      rect(50, 50, 50, 50);
    }
    
    void mouseReleased() { 
    
      loop();
    
      if (mouseX > 149 && mouseX < 200 && mouseY > 49 && mouseY < 101) {
        if (value1 == 0)
          value1 = 255;
        else  
        value1 = 0;
      } 
      // ----
      else if (mouseX > 49 && mouseX < 100 && mouseY > 209 && mouseY < 250) {
        if (value2 == 0)
          value2 = 255;
        else  
        value2 = 0;
      } 
      // ---
      else if (value3 == 0 & (mouseX > 149 && mouseX < 200 && mouseY > 209 && mouseY < 250)) { 
        value3 = 255;
      } else { 
        value3 = 0;
      } 
      if (value4 == 0 & (mouseX > 49 && mouseX < 100 && mouseY > 49 && mouseY < 101)) { 
        value4 = 255;
      } else { 
        value4 = 0;
      }
    }
    //
    
Sign In or Register to comment.