Game Development Reference
In-Depth Information
As you look at this method, you will see that it does not do a whole lot at the moment. It
first removes the
playerNode
from the scene, and then it sets node to
nil
. After that,
it tests the
gameResult Bool
passed to it and prints whether the player won the game.
Don't worry too much about this method at the moment. You will be modifying this code
soon enough. For now, add this method to the bottom of the
GameScene
, and let's get to
determining whether the player lost the game.
Note
Numbers like 6400.0 and 7000.0 may seem like crazy numbers when the
height of the display is nowhere near either of these numbers. Remember, you
added the
playerNode
to the
foregroundNode
, and you have been mov-
ing the
foregroundNode
down while the
playerNode
, virtually, contin-
ues up the scene. This is how the player's y-position is so much higher than the
height of the device's viewport.
Losing the Game
You now know when the player has won the game. It is now time to test to see whether
the player has lost the game. To do this, go back to the
update()
method and add the
following
else if
to the bottom of the
if
statement (directly following the
else if
you just added):
else if playerNode!.position.y < 0.0 {
gameOverWithResult(false)
}
This bit of code is pretty easy to understand. If the
playerNode
's y-position is less than
0.0
, then the player has fallen off the bottom of the scene, and the
gameOver-
WithResult()
method is called with the value false being passed to it, which indicates
that the player has lost the game.
There is one last thing you need to do before transitioning to a new scene. In the
gameOverWithResult()
method, you removed the
playerNode
from the parent
and then set it to
nil
. This is perfectly fine, but you need to make sure you do not try to
use this property without checking to see whether it is
nil
first. There are only two
places you currently do this.
The first is in the
update()
method with each time you are checking the
player-
Node
's position. To make sure you don't dereference a
nil playerNode
, you need to