Button-controlled scene changes



We've gotten away so far with just having the user click anywhere at all in order to change scenes. But we've realized there's a drawback to that approach: we can't use clicks within scenes for any sort of additional interaction. The way that many games and apps solve that is by adding specific UI elements, like menus and buttons, and only navigating scenes upon interaction with a specific UI element. Let's add a button in the top right to control the scenes in our program.



What is a "button"? It's two things really: 1) the visual indicator that an area is clickable and 2) the logic that makes that area respond to clicks. Let's start with the visual indicator, a rect() with some text(), and wrap it in a function, in case we want to call it multiple times:

var drawButton = function() {
fill(81, 166, 31);
rect(340, 10, 50, 25);
fill(255, 255, 255);
textSize(16);
text("NEXT", 344, 29);
};

Now where should we call it? We definitely need to call it when we draw the first scene, so they have a way of getting to the next scene:

drawScene1();
drawButton();

We also need to display it on every subsequent scene. We could call it from inside every scene drawing function, but there's a simpler way: just stick it at the end of our mouseClicked function, to make sure it's called after we draw every scene:

mouseClicked = function() {
if (currentScene === 1) {
drawScene2();
} else if (currentScene === 2) {
drawScene3();
} else if (currentScene === 3) {
drawScene4();
} else if (currentScene === 4) {
drawScene5();
} else if (currentScene === 5) {
drawScene1();
}
drawButton();
};

Okay, I lied, it's not quite that simple. With the above code, we would see the button in every scene except one. Can you figure out which one? I'll give you a few seconds...stop reading this! Are you thinking about it? Okay, okay, it's the animated scene. That's because the code inside draw() will draw scene 4 on top of the button immediately, so we need to add it to the end of that function as well:

draw = function() {
if (currentScene === 4) {
drawScene4();
}
drawButton();
};

And hey, just in case some enterprising individual decides to drag babies all over the next button, let's call it at the end of mouseDragged as well:

mouseDragged = function() {
if (currentScene === 5) {
image(getImage("creatures/BabyWinston"), mouseX-20, mouseY-20);
}
drawButton();
};

Woo! Now we've got a button in every scene, all the time. Check it out: