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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With