Xcode SpriteKit how to adapt label in GameScene with different screen sizes?

Viewed 188

I have a label in GameScene, there is no auto layout to use here, how I can use CGpoint to make sure this label stay at the same position on different screens.

enter image description here

Below is the code where I put my score label

scoreLabel?.position = CGPoint(x: -size.width / 2 + 120, y: size.height / 2 - 150)
3 Answers
let scoreLabel = //insert functionality of scoreLabel here

scoreLabel?.position = CGPoint(x: size.width + //insert dimention, 
y: size.height + //insert dimension)

self.addChild(scoreLabel)

seeing your previous comment, I would suggest you use the following functions, which change the dimensions when they are run on different screen sizes:

AspectFill
AspectFit
ResizeFill

Here is a link that could help you on how to use these functions: Sprite Kit Scene Editor GameScene.sks scene width and height

Hope this helps!

Here is what I put in my View Controller:

var h, w = 1000

class GameViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if let view = self.view as! SKView? {
            w = view.frame.width / (view.frame.height / 1000)
            let scene = GameScene(size: CGSize(width: w, height: h))

            scene.scaleMode = .aspectFill
            view.presentScene(scene)
        }
        
    }
}

It's handy to know that I make the height of any device 1000. It's much easier to make it universal.

Then I place everything percentage-wise on the screen.

label.position.x = w/2
label.position.y = h/2

label2.position.x = w/2
label2.position.y = h/2 - 50

These lines of code will place 2 labels in the center of the screen. Even if you rotate your device, and even if you use different sized devices. That - 50 I used will always stay the same.

My main takeaway: I create global states of the relative size of the screen.

Helpful tip: I always make my scene's anchor point to be .zero. That way, the min width and height are always 0, and the max height is always 1000.

Related