Search code examples
swiftskspritenodesktilemapnode

How to position SKTilemap Scene in the middle of screen in Swift


I have created a TilemapScene (CKTilemapScene.sks) in Swift 5. This is basically to lay a tile map background of my game project. Refer to the second screenshot below.

Then, in my main swift code, I load all the background with the standard codes. But, somehow the tile map is not centered. Refer to the first screenshot below . But, at the bottom left of the screen. I tried to play with anchor point. That doesn't help. Did I set anything wrong?

import UIKit import SpriteKit import GameplayKit

class GameViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    
    if let view = self.view as! SKView? {

        if let scene = SKScene(fileNamed: "CKTilemapScene") {
            
            // Present the scene
            view.presentScene(scene)
        }
        
        view.ignoresSiblingOrder = true
        
        view.showsFPS = true
        view.showsNodeCount = true
        view.showsPhysics = true
    }
}

override var shouldAutorotate: Bool {
    return true
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    if UIDevice.current.userInterfaceIdiom == .phone {
        return .landscape
        //.allButUpsideDown
    } else {
        return .all
    }
}

This is the outcome, tile map not centralised

This is the screenshot from the Attribute Inspector


Solution

  • Set the position of SKScene to the SKView's center.

    override func viewDidLoad() {
        super.viewDidLoad()
    
        if let view = view as? SKView {
            if let scene = SKScene(fileNamed: "CKTilemapScene") {
                scene.position = view.center
                view.presentScene(scene)
            }
        }
        //...
    }