Game Development Reference
In-Depth Information
of the collision. Later in the game you will be adding a fuel element so that the orbs will
provide fuel for the player to ascend higher and higher.
To be able to detect when
SKNode
s come into contact with each other, you first imple-
ment the Sprite Kit protocol
SKPhysicsContactDelegate
in the
GameScene
class
and then implement the methods needed in your game. The
SKPhysic-
sContactDelegate
protocol defines two methods used to detect when
SKNode
s
touch each other: the
didBeginContact
and the
didEndContact()
methods. The
following snippet shows the protocol:
protocol SKPhysicsContactDelegate : NSObjectProtocol {
optional func didBeginContact(contact:
SKPhysicsContact!)
optional func didEndContact(contact: SKPhysicsContact!)
}
The method names make their function pretty straightforward. The
didBe-
ginContact()
method is invoked when the contact first begins, and the
didEndContact()
method is invoked when contact ends. For this game, you are inter-
ested only in the first method,
didBeginContact()
, because you don't want the
playerNode
to pass through the orb. You want the orb to be removed from the scene as
soon as the
playerNode
contacts the orb.
Go back to the
GameScene.swift
file and change the class definition to the following:
class GameScene: SKScene, SKPhysicsContactDelegate
After you change your class definition, add this implementation of the
didBe-
ginContact()
method to the end of the
GameScene
class:
func didBeginContact(contact: SKPhysicsContact!) {
println("There has been contact.")
}
Finally, you need to make the
GameScene
the delegate of the scene's
physic-
sWorld.contactDelegate
. This is done by adding the following line in the
GameScene.init(size: CGSize)
method directly after the call to the
su-
per.init(size: size)
:
physicsWorld.contactDelegate = self