0

I’m trying to add a mouse press event to an image which I think is possible since I’ve seen may questions posted about it on the forum. However I have an image of a play button. I want to use this image as a button to play/pause music. So far I haven’t found anything on mouse press for images to play music. Does anyone know where I can read more about this specific topic? Still looking through documentation haven’t found anything yet. Heres some snip it of my code:

PImage play;
play = loadImage("play.png"); // in setup
imageMode(CORNER); // in draw
image(pause, 80, 15, 50, 50); // in draw

1 Answers1

0

If you want something to happen when you click somewhere, you got to compare the click's coordinates to the object's coordinates.

Here's an example that you can adapt to your needs:

void mouseClicked() {
  if (mouseX >= playButton.x && mouseX <= playButton.x + playButton.width && mouseY >= playButton.y && mouseY <= playButton.height) {
    // user clicked on the play button
  }

  // another image in case you want to check for more than one button:
  if (mouseX >= pauseButton.x && mouseX <= pauseButton.x + pauseButton.width && mouseY >= pauseButton.y && mouseY <= pauseButton.height) {
    // user clicked on the pause button
  }
}

playButton.something and pauseButton.something being the coordinates of whatever you want to catch clicks on, not necessarily a full-on object.

Have fun!

laancelot
  • 3,138
  • 2
  • 14
  • 21
  • Yes I actually figured this out after posting, thanks! Any chance you know how to do this with multiple images? I have 2 other images where I did the same thing and they didn't work. It only worked for one image. @laancelot –  Oct 18 '20 at 04:39
  • @charmy Are you at ease wit object oriented programming? The easiest way is to make every visible object inherit from a common class, throw them in an arraylist and check them all in a `for` loop. [This answer](https://stackoverflow.com/questions/60849384/collision-detection-only-works-when-object-hits-right-in-the-centre/60859519#60859519) has some good cues with that. If you're not into OOP you can use the code I just posted, but in the `mouseClicked()` method you can check for a click on every objects which interests you. I'll adapt the code to show what I mean in a sec. – laancelot Oct 18 '20 at 04:57
  • Could I possibly ask you a quick question in chat @laancelot? I got all buttons to work except for one and I think it may be how I'm calling a method in the if statement but I'm not sure. I just got back to processing after years. I'll make it quick –  Oct 18 '20 at 05:08
  • Go on, although I'll probably just get this tomorrow! – laancelot Oct 18 '20 at 06:19
  • I posted a question about it here if you could please take a look: https://stackoverflow.com/questions/64410109/songs-not-shuffling-for-button-processing @laancelot –  Oct 18 '20 at 06:20