Reputation: 1708
I am trying to make a number appear in the middle of an SKShapeNode. However, for some reason when I add the SKLabelNode as a child of the shape node, it does not appear despite the fact that the SKShapeNode does appear. I added the same label as a child of the SKScene and it appeared just fine. Here is the code for the custom class:
class Dot: SKShapeNode {
var numLabel = SKLabelNode(fontNamed: "MarkerFelt-Wide")
func setNumber(i: Int) {
numLabel.text = String(i)
numLabel.fontColor = UIColor.whiteColor()
numLabel.fontSize = 200
numLabel.setScale(numLabel.frame.width / self.frame.width / 2)
numLabel.position = CGPointMake(self.frame.midX ,self.frame.midY)
self.addChild(numLabel)
}
}
I call dot.setNumber(1)
but nothing happens. Please let me know if you find the issue. Thanks!
Upvotes: 2
Views: 876
Reputation: 2666
After much trial and error, reteaching myself how SKNodes
work differently than UIViews
, I think the reason for your problem is as follows: the .position
property in sprite kit is not the position of the corner of the node, but the center of it. Also, when setting an SKNode
as a child of another SKNode
, its position is based on its parent, not the scene. So instead of setting the numLabel
to midX
and midY
it should rather be:
numLabel.position = CGPointMake(0, 0)
However, for some reason the y
value is still not correct, at least in the code that I am using. It may be due to the way that you are scaling the numLabel
. So I sort of fixed it with the code:
numLabel.position = CGPointMake(0, -(numLabel.frame.height / 2))
Still, this is not perfect.
With this new information, if you are still not able to figure it out, I will look further into getting the exact position. But keep in mind my answer at the beginning of this post.
Upvotes: 2