Trouble with mousePressed

I’m trying to make one part of the code transition to another with no luck. I’m trying to use mousePressed but it seems like the scene only appears for a moment before disappearing again. Is thi because of void draw()?

here’s the code for anyone interested:

int y=0;
void setup()
{
  size(800,500);
}

void draw()
{
  if(y<=200&&y>=0)
  {
   y=y+1;
  }
  background(12,23,34);
  textSize(50);
  text("help me",350,y);
  if(mousePressed==true)
  {
   mainMenu();
  }
}

void mainMenu()
{
  background(56,97,72);
  text("please",350,78);
}
1 Like

you better use the

void mousePressed(){}

to set a boolean OR integer
what you can use in draw to switch your view.

@kll
on top, I put boolean mouseClicked=false, but the code still doesn’t work. I’m also not really clear on booleans, so maybe you could explain it a little…?

void mousePressed()
{
  if(mousePressed==true)
  {
    mouseClicked=true;
  }
  if(mouseClicked==true)
  {
    mainMenu();
  }
}

Hey there!
the mousePressed() method is called everytime you press the mouse having an if statement condition within means it only gets checked per mousePressed() click. i.e. Your main menu method will only be drawn everytime you press your mouse you should attempt using a boolean variable and only the if else logic within the mousePressed to set the variables = false or true , the mainMenu method should be called from the draw method within its own if condition

@kll @InferNova
Thank you to you both! My code is working now, using

if(mousePressed)
  {
    mouseClicked=true;
  }
  if(mouseClicked==true)
  {
    mainMenu();
  }

I do have an issue though, since I have to switch back and forth a lot, I find myself making a new boolean each time(to replace mouseClicked since the destinations are different). Is there a shortcut or am I supposed to keep making new booleans?

void draw(){
	background(255);
	if( mouseClick == true) mainMenu();
}
void mousePressed(){
	mouseClick = true;
}

Hey there!
This code will be more effective as having mousePressed within draw() like that will cause the mouse once pressed to enter and be called many times a s draw() updates 60 fps. So by that I mean you press the mouse once but draw will keep the executing the if statement and it can lead you problems down the line. Better practice to keep it in it’s method for event calls.

To avoid making alot of boolean variables you could assign a state to each of your statements. So for example accessing the mainMenu could be state 0 but once your in the main menu going further depending on what you can have the state to be 1 or 2. This allows different instances of screens to exist.

1 Like

@InferNova
thank you! I’ll try out what you said about assigning numbers, maybe that’ll be easier for me. Also, thanks for the tip about having separate functions for mousePressed!