Game Development Reference
In-Depth Information
Now that you know how to use
SKLabelNode
, it is time to put it to some good use. As
mentioned at the beginning of this topic, the goal of this game is to collect as many orbs
as you can without colliding with a black hole or running out of impulses.
In this section, you will finally add some scoring to the game. Specifically, you will add
an
SKLabelNode
to the top right of the scene. The original text will be “SCORE : 0.”
This numeric value will increment each time the
playerNode
comes into contact with
an orb node—the more orbs collected, the higher your score. Let's make this happen.
The first step you need to do to add a scoring label to the
GameScene
is to create a vari-
able to hold the score (the number of orbs collected) and an
SKLabelNode
constant to
hold the label. This can be accomplished with the following two lines of code:
var score = 0
let scoreTextNode = SKLabelNode(fontNamed: "Copperplate")
This code is pretty straightforward. It creates an integer variable named
score
and sets it
to 0, which makes sense at the beginning of a game, and then it creates an
SKLa-
belNode
with a font of Copperplate. I chose Copperplate because I thought it looked
good with the images already in place, but you can choose whatever you like. After look-
ing at this code, add it to the end of the
GameScene
's declaration section immediately
before the first
init()
method:
var score = 0
let scoreTextNode = SKLabelNode(fontNamed: "Copperplate")
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
The next thing you need to do is set all of the
SKLabelNode
's properties and add it to
the
GameScene
. This is accomplished in the following snippet:
scoreTextNode.text = "SCORE : \(score)"
scoreTextNode.fontSize = 20
scoreTextNode.fontColor = SKColor.whiteColor()
scoreTextNode.position =
CGPointMake(size.width - 10,
size.height - 20)
scoreTextNode.horizontalAlignmentMode
= SKLabelHorizontalAlignmentMode.Right