I am wanting to create a SKLabelNode that is in the top left corner of every device. Also, to the left of the label in the top left corner I want an image that is a coin to show that this is the current coin count label. Every time I place my label in the corner on my iPhone 6s+ it isn't in the corner on my iPad.
Here is my code so far:
cornerCoin.position = CGPoint(x: screenWidth / -3.1, y: screenHeight / 3.175)
cornerCoin.zPosition = 10
cameraNode.addChild(cornerCoin)
coinLabel.position = CGPoint(x: screenWidth / -2.4, y: screenHeight / 8)
coinLabel.zPosition = 1
coinLabel.fontSize = 50
coinLabel.fontColor = UIColor.black
coinLabel.fontName = "04b19"
cameraNode.addChild(coinLabel)
Personally, I would not be tracking screenWidth/screenHeight, it goes against the foundation of SpriteKit to begin with (Your scene behaves as your virtual screen, this is how you should handle everything inside of it) Instead, what you should do is convert from screen to scene, this way regardless of scale mode or anchor point, your label is where you want it to be.
To get the top right corner of your view converted to your scene, you do
if let view = scene.view
{
let topRightPos = view.convert(CGPoint(x:view.frame.maxX,y:view.frame.minY),to:scene)
let camTopRight = scene.convert(topRightPos,to:cameraNode)
}
Now we know where our top right position is:
We can do
if let view = scene.view
{
let topRightPos = view.convert(CGPoint(x:view.frame.maxX,y:view.frame.minY),to:scene)
let camTopRight = scene.convert(topRightPos,to:cameraNode)
coinLabel.position = camTopRight
coinLabel.zPosition = 1
coinLabel.fontSize = 50
coinLabel.fontColor = UIColor.black
coinLabel.fontName = "04b19"
coinLabel.horizontalAlighmentMode = .right
coinLabel.verticalAlighmentMode = .top
cameraNode.addChild(coinLabel)
}
to right align our label so that the text always extends to the left, then to add the coin, we do:
if let view = scene.view
{
let topRightPos = view.convert(CGPoint(x:view.frame.maxX,y:view.frame.minY),to:scene)
let camTopRight = scene.convert(topRightPos,to:cameraNode)
coinLabel.position = camTopRight
coinLabel.zPosition = 1
coinLabel.fontSize = 50
coinLabel.fontColor = UIColor.black
coinLabel.fontName = "04b19"
coinLabel.horizontalAlighmentMode = .right
coinLabel.verticalAlighmentMode = .top
cameraNode.addChild(coinLabel)
cornerCoin.position = CGGPoint(x:0.0,y:coinLabel.frame.midY)
cornerCoin.anchorPoint = CGPoint(x:1.0,y:0.5)
cornerCoin.zPosition = 10
cameraNode.addChild(cornerCoin)
}
Our label should now be in the top right position of our camera, and the coin should be to the left of our label centered vertically with the text.
You may want to play with how your label is positioned if you do not like the look of top alignment.