Mousepressed in certain area (toggle on/off)

I’m new to processing and this should be really easy to solve but I’m kind of stuck. So basicially, this is a snippet of my programm.

What I want to achieve is that if I click on a button, it shows another picture and if I click on it again, the picture should disappear. I’ve looked through google and other forums but I’m not really sure on what to look for since the results for “boolean” and “mouse clicked” and so on, vary and can be quite extensive.

I’m sorry if this is really obvious…

Problem: I’m not sure how to include the “else”, so that if I click on the designated area, it turns off.

I tried if else (mousePressed) and then the mouse locations, and noticed I have to include another “if” to get the “lightbutton1 = false” in but it didn’t work.

    void draw ()
    {
      image(BG1,0,0); 
      if(lightbutton1) {
      image(light,0,0); }
    }

    void mousePressed () {
      if  (mouseX > 720 && mouseY < 477 && mouseX < 800 && mouseY > 420) {
        lightbutton1 = false;
      }
      else
      { 
        lightbutton1 = true; 
      }
    }
1 Like

You are very close. Your if/else is correct. Your problems are:

  1. not including background() in draw. So you click and draw stops drawing the image, but you can’t tell it worked because the last frame isn’t wiped.
  2. use mouseReleased, otherwise you might have multiple flips of the variable during one long click.
  3. To make things simpler, you can do this:
if  (mouseX > 720 && mouseY < 477 && mouseX < 800 && mouseY > 420) {
  lightbutton1 = !lightbutton1;
}

That “flips” the boolean value; true=false, false=true. Then you don’t need the else – although your code with else and the simpler example are both correct and do the same thing.

boolean show;
void draw(){
  background(0); // clear frame!
  if(show){
    rect(10, 10, 80, 80);
  }
}
void mouseReleased(){ // only change once when click ends
  show = !show; // flip value
}