Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Processing- how to write; "On mouse click in region". For effect of clicking a button

I was wondering why this code doesn't work as intended.

void mousePressed() {

    if (mouseX > width-50 && mouseX < width && mouseY > height-50 && mouseY < height)
    { 
        img = loadImage("doraemon.png");
        image(img, 0, 0, width, height);
    }

I want it so that when I click on an image that says 'next', I can show a different image on the background, and if clicked again, show another background image and so on.

if (mouseX > width-50 && mouseX < width && mouseY > height-50 && mouseY < height)

^This code snippet states where the button 'next' is. When I run this code, I get an image while hovering over the condition, but I want the image to appear after I press the button.

Does anyone know how to write that?

I need something like

 if (mousePressed == condition)
     { 
      then change image
     }

Please help. I really appreciate it!

like image 365
bisuke Avatar asked Nov 09 '22 09:11

bisuke


1 Answers

You're trying to cram all of your logic into the mousePressed() function. Instead, you need to split your logic up between the mousePressed() function and the draw() function. Use variables to keep track of what should be drawn. Adjust those variables in the mousePressed() function. Use those variables to figure out what to draw in the draw() function.

A simple example might look like this:

boolean showButton1 = true;

void setup() {
  size(200, 200);
}

void mousePressed() {
  if (mouseX < 100 && mouseY < 100) {
    //button 1 was just clicked, show button 2 instead
    showButton1 = false;
  } else if (mouseX > 100 && mouseY > 100) {
    //button 2 was just clicked, show button 1 instead
    showButton1 = true;
  }
}

void draw() {

  background(0);

  if (showButton1) { //draw the first button
    fill(255, 0, 0);
    rect(0, 0, 100, 100);
  } else { //draw the second button
    fill(0, 255, 0);
    rect(100, 100, 100, 100);
  }
}

Also, you shouldn't call loadImage() from the mousePressed() or draw() functions. Instead, load your images from the setup() function, and store them in variables that you can use later.

like image 101
Kevin Workman Avatar answered Dec 26 '22 14:12

Kevin Workman