Game Development Reference
In-Depth Information
surround the body of the
update()
method with an
if
, checking to make sure the
playerNode
property is not
nil
. You can see this change in the new
update()
meth-
od shown here:
override func update(currentTime: NSTimeInterval) {
if playerNode != nil {
if playerNode!.position.y >= 180.0
&& playerNode!.position.y < 6400.0 {
backgroundNode!.position =
CGPointMake(self.backgroundNode!.position.x,
-((playerNode!.position.y - 180.0)/8));
backgroundStarsNode!.position =
CGPointMake(self.backgroundStarsNode!.position.x,
-((playerNode!.position.y - 180.0)/6));
backgroundPlanetNode!.position =
CGPointMake(backgroundPlanetNode!.position.x,
-((playerNode!.position.y - 180.0)/8));
foregroundNode!.position =
CGPointMake(self.foregroundNode!.position.x,
-(playerNode!.position.y - 180.0));
}
else if playerNode!.position.y > 7000.0 {
gameOverWithResult(true)
}
else if playerNode!.position.y
+ playerNode!.size.height < 0.0 {
gameOverWithResult(false)
}
}
}
After taking a look at these changes, modify your
update()
to look like this one and
let's move on.
The second place you need to make sure you are not dereferencing a
nil playerNode
is in the
didSimulatePhysics()
method. In this method, you are using the
play-
erNode
's
physicsBody
and
position
properties. To prevent the dereferencing of a
nil
value, you should surround the entire body of the method with an
if
that checks to
see whether the
playerNode
is
nil
. This change is shown here: