For many of the functions we have created for our game objects, we need to activate the event listeners so that they will run the code and then disable them when game play has stopped. To add game listeners, follow these steps:
gameListeners()
, which will also have a parameter called event
. This should be added right after the gameLevel2()
function:function gameListeners(event)
if
statement:if event == "add" then Runtime:addEventListener("accelerometer", movePaddle) Runtime:addEventListener("enterFrame", updateBall) paddle:addEventListener("collision", bounce) ball:addEventListener("collision", removeBrick) paddle:addEventListener("touch", dragPaddle)
elseif
statement for the event listeners that will remove the events and then close the function:elseif event == "remove" then Runtime:removeEventListener("accelerometer", movePaddle) Runtime:removeEventListener("enterFrame", updateBall) paddle:removeEventListener("collision", bounce) ball:removeEventListener("collision", removeBrick) paddle:removeEventListener("touch", dragPaddle) end end
function gameListeners()
to work properly, we need to instantiate it in the startGame()
function using the "add"
string in the parameter. Place it before the end of the function:gameListeners("add")
alertScreen()
function, add the "remove"
string in the parameter and place it at the start of the function:gameListeners("remove")
There are two sets of if
statements for the event
parameter: "add"
and "remove"
.
All the event listeners in this function play an important role in making the game run. The "accelerometer"
and "enterframe"
events are used as runtime events since they have no specific target.
Both the paddle
and ball
objects have "collision"
events that will carry out their purpose in any object contact made.
The "touch"
event allows the user to touch and drag the paddle so that it can move back and forth in the simulator.
Notice that when event == "remove"
, it removes all the event listeners that were active in the game. When the game starts, gameListeners("add")
is activated. When a win or lose condition is achieved, gameListeners("remove")
is activated.
What if we decided to flip the game upside down, that is, have the paddle placed near the top of the screen, the ball below the paddle, and the group of bricks closer to the bottom of the screen?
Things you'll have to consider are as follows:
As you can see, there are a couple of things to consider before switching values from negative to positive and vice versa. Be sure to verify your logic and ensure that it makes sense when creating this new variation.