We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello!
I am making a "game box". I have a simple main menu where i want to access my 2 processing games from. I am using keys for this, so if(keyPressed) { if (key =='1') { stage = 1; if '2' is pressed then stage = 2, same with stage 3. Problem is that when i press '2', i move to stage 2, but when i press 1 or 3, nothing happens. I've tried printing the stage to the console and it writes 1 when i start it up, but when i go to either stage 2 or 3 prints once and then it stops.
Here's a bit (starts in stage 1 defined in setup): if(keyPressed) { if (key == '1') { stage = 1; } if (key == '2') { stage = 2; } if (key == '3') { stage = 3; } }
if (stage == 2){ background(255,0,0); //red Game1 code is supposed to go here println(stage);
if(keyPressed) { if (key == '1') { stage = 1; } if (key == '2') { stage = 2; } if (key == '3') { stage = 3; } } } if (stage == 3){ background(0,255,0); //green Game2 code is supposed to go here println(stage);
if(keyPressed) { if (key == '1') { stage = 1; } if (key == '2') { stage = 2; } if (key == '3') { stage = 3; } } }
Answers
I have now pasted the game into one of the stages and have encountered another problem. I'm using a void mousePressed and i get a "unexpected token:void error.
several issues here.
First:
if(keyPressed
takes ONE key press 3 or 4 timesinstead of using
if(keyPressed...
better use the function of the same name:second use
if...else if ...
instead ofif...if...if...
(also indraw()
!!!)Third post runnable code or a mcve:
https://stackoverflow.com/help/mcve
Thank you for your response Chrisir! I figured out the if.. else if thing before i saw your reply. In response to the first issue you addressed, if i copy the part you wrote and use void keyPressed instead of if (keyPressed) i get the "unexpeced token: void" error.
... Which is impossible for us to debug without seeing the runnable code or an MCVE. Which is why you should post runnable code or an MVCE.
Of course, here you go. I've made it sort of "working" by replacing my voids with if's. This obviously causes an issue which you will see if you look at it. https://pastebin.com/u3Hsnsji
The VERY FIRST thing to fix is to move any line that has "loadImage" in it into
setup()
! You do NOT want to be reloading your images 60 times a second, right? That's what you're doing by having those calls indraw()
!Next, understand the difference between "void keyPressed()" and "keyPressed". The former is a top-level function, like draw() or setup(), that is called once when a key is pressed. The latter is a boolean variable that is true if a key is being held down. The function is what Chrisir is suggesting you use!
Now I can't test this without your images, but I shuffled things about a bit, and this is the result: