Search code examples
iosswiftsprite-kituniversalskcameranode

Using SKCameraNode for an Universal App SWIFT


I develop an universal game using Sprite Kit Level editor on Xcode 8 beta 4.

My scene in the level editor does 750x3334. In my scene I have a background image, the background image is adjusted to the scene size.

  • Scene anchor point = (0,1) Top left

  • Background anchor point = (0,1) Top left.

I need a camera inside my scene.

I set a SKCameraNode with a scale (1,1), the position of the camera is the center of my scene.

camera

To create the scene :

 if let scene = GKScene(fileNamed: "GameScene") {

        if let sceneNode = scene.rootNode as! GameScene? {

            // Copy gameplay related content over to the scene
            sceneNode.entities = scene.entities
            sceneNode.graphs = scene.graphs
            sceneNode.scaleMode = .aspectFill

            if let view = self.view as! SKView? {

                view.presentScene(sceneNode)
                view.ignoresSiblingOrder = true
                view.showsFPS = true
                view.showsNodeCount = true
            }
        }
    }

When the game is launched, my camera has to be set to have the top of the background equal to the top edge of the device.

To do that:

override func sceneDidLoad() {
    camera?.position.y = -UIScreen.main.nativeBounds.size.height/2
}

For the iPhone 6, it works perfectly. For the iPhone 5, 6+, I have a blank area (out of the scene) at the top edge.

explain

So maybe my logic is wrong...


Solution

  • You should not be touching screen size, you need to be working with the scene size. .AspectFill retains the same scene size, regardless of device, the only scaleMode that changes scene size is .ResizeFill

    To get your camera at center, you need to do

    camera.position = CGPointMake(scene.frame.size.width / 2, scene.frame.size.height / 2)  
    

    Note, scene may be self, I do not know where you will be using this code