JulieFunk
JulieFunk

Reputation: 53

mousePressed within certain region in Processing

I have an background image that I want users to think they're interacting with through Processing. The image has a list of words on it and when the user clicks on the region surrounding the word, I want sound to play and a serial number sent to Arduino.

All that aside, I can't get the mousePressed code right. I'm testing it with println("yikes") right now, and now matter where I click on the screen I get "yikes".

On top of all of that, I'm getting errors on else that I can't figure out. Help appreciated.

  void setup() {
  size(1475, 995);
  // The image file must be in the data folder of the current sketch 
  // to load successfully
  img = loadImage("PaceTaker.jpg");  // Load the image into the program
}

void draw() {
  // Displays the image at its actual size at point (0,0)
  image(img, 0, 0);
}
void mousePressed() {
  if (mouseX>105 && mouseX<337 && mouseY>696 && mouseY<714); 
  {
    println("yikes");
    stroke(0);
  }
  else println("hello"));
}

Upvotes: 1

Views: 1276

Answers (1)

Kevin Workman
Kevin Workman

Reputation: 42176

Pay close attention to this line:

if (mouseX>105 && mouseX<337 && mouseY>696 && mouseY<714); 

Notice that it ends in a ; semicolon.

This basically says "if the mouse is inside the region, do nothing." Then it gets to the next block of code and always runs it, which is why you're always seeing the "yikes" printed out.

You also have a compilation error on this line:

else println("hello"));

Because it has an extra ) closing parenthesis.

To fix both these problems, get into the habit of always using { } curly brackets with your if and else statements, even if they're just one line, and always check for stray ; semicolons:

  if (mouseX>105 && mouseX<337 && mouseY>696 && mouseY<714) {
    println("yikes");
    stroke(0);
  } else {
    println("hello");
  }

Upvotes: 2

Related Questions