Sweeper
Sweeper

Reputation: 271040

How can I create a pause label in SpriteKit?

I want to create a "PAUSED" sign that appears when the game is paused. It should have a white background and the text "PAUSED".

--------
|PAUSED|
--------

The docs says that you can't subclass a node to do custom drawing, which is sad :(

So I decided to use a sprite node with white color and a label node to do this. I can then add the label node as a child of the sprite node:

let pauseText = SKLabelNode(text: "PAUSED")
pauseText.fontColor = UIColor.blackColor()
pauseText.fontName = "Times New Roman"
pauseText.fontSize = 30
pauseNode = SKSpriteNode(color: UIColor.whiteColor(), size: pauseText.frame.size)
pauseNode.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
pauseText.position = CGPointMake(CGRectGetMidX(pauseNode.frame), CGRectGetMidY(pauseNode.frame))
pauseNode.zPosition = 999
pauseNode.addChild(pauseText)

where pauseNode is the sprite node and pauseText is the label node.

But this doesn't seem to work. The sprite node shows up as a thin rectangle and I can't see any text in it.

How to do this?

Upvotes: 1

Views: 97

Answers (1)

Craig Siemens
Craig Siemens

Reputation: 13276

The value you're assigning to pauseText.position will cause the text be drawn off the screen.

From the SKNode docs:

Every node in a node tree provides a coordinate system to its children. After a child is added to the node tree, it is positioned inside its parent’s coordinate system by setting its position properties.

If you set the position to (0, 0) you'll see the text but it is up a bit too high. Then just change the y value so it is vertically centered in its parent.

pauseText.position = CGPointMake(0, -pauseNode.frame.height / 2)

Which will show

enter image description here


On a side node, I learned that fontName can be either a font name or a font family name so thats cool.

Upvotes: 2

Related Questions