Switching between multiple Screens in a Processing game

13Jul, 2016

In this tutorial, we would be adding a Menu screen and a game over screen to the bouncing ball game that was created in the last tutorial.   So make sure you download the .pde file from the last post.

Here’s what we will be creating:

Since Processing does not give any standard api for switching between scenes, we would need to improvise.   The best way to conveniently transit from screen to screen is to use a variable to hold information about the current screen running.

For this example, we would create a String variable and call it currentScreen.   So go to the very top of the code and type the following:

String currentScreen = “menu”;

The next step is to edit the draw method and make it check the current position of the screen so it can determine what to draw.  ie If the currentScreen variable value is equal to “menu”, then it draws a text, if it is “gameplay”, it plays the game and if the variable value is “game over”, then it shows the Game Over text.   To do this,  change the content of the draw method to:

The above code looks long but it’s actually easy to understand.   The first if statement simply checks if the current screen is “menu” and Writes the text to the screen.   The else if statement checks if the  currentScreen

is equal to “gameplay” and simply executes the code that was written in the last post.

Now the next step is to check if any key was pressed.   If a key is pressed, then it checks the current screen.   If the current screen is menu or gameover, then it switches to game play.   To listen for key events in processing, we use the

method.   To do this, add the following to your code:

And that’s it.

Feel free to ask your questions in the comment box below 🙂


1 Comment

  • JR April 6, 2020 @ 10:22 pm

    i cant seem to get this right… is this correct or did i mess up horribly?

Leave a Reply

Your email address will not be published. Required fields are marked *