Animator Joe
Animator Joe

Reputation: 69

SKLabelNode Not Showing [SpriteKit]

I created a SKShapeNode called smallScreen and an SKLabelNode with the name screenLabel.

I later attempted to display screenLabel in smallScreen. When I ran the code however, it didn't work. I tried adding screenLabel as a child to self, and that seemed to allow the text to display. Whenever I added screenLabel as a child node to smallScreen, it wouldn't display. Please help, much thanks.

    self.smallScreen = (self.childNodeWithName("screen") as? SKShapeNode)!
    self.smallScreen.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height * 2/3)

    screenLabel.text = "Screen"
    screenLabel.fontSize = 30
    screenLabel.fontColor = UIColor.redColor()
    screenLabel.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height * 2/3)
    screenLabel.hidden = false
    self.smallScreen.addChild(screenLabel)

Upvotes: 1

Views: 834

Answers (1)

Alessandro Ornano
Alessandro Ornano

Reputation: 35412

In Sprite-kit by default, a scene’s origin is placed in the lower-left corner of the view. Its default value is CGPointZero and you can’t change it. (source).

A sprite’s (SKSpriteNode) anchor point defaults to (0.5,0.5), which corresponds to the center of the frame (source).

SKShapeNode does not have an anchorPoint.

LearnCocos2D answered on this issue:

When you use an image you may need to align it on its node's position. There's no other way to do so but through anchorPoint because the image itself can't be modified (not easily anyway).

When you create a shape you have full control over the alignment of the shape through CGPath. You can simply translate the path to change the shape's alignment relative to the node's position.

This is my interpretation, not fact.

So , what happened to your code?

I don't know how you have initialized your shape, I make just an example:

/* Create a Shape Node representing a rect centered at the Node's origin. */
    @available(iOS 8.0, *)
    public convenience init(rectOfSize size: CGSize)

So we create the shape like this:

self.smallScreen = SKShapeNode.init(rectOfSize: CGSizeMake(200,200))

First, you place your SKShapeNode to the X center of the screen for the X coordinates, and Y = self.frame.size.height * 2/3. In fact, your smallScreen is visible.

Speaking about your label, you have add it to the smallScreen, so screenLabel must respect the alignment of his parent. In fact you can see your label simply by making this change:

From:

   screenLabel.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height * 2/3)

To:

screenLabel.position = CGPointZero

and your label is positioned to the center of the smallScreen according to the alignment of his parent.

Upvotes: 1

Related Questions