Search code examples
swiftsprite-kitxcode6scene

Scene size in Xcode 6 / SpriteKit / Swift


I've been getting stuck doing what should be really simple stuff in Xcode, I am trying to add a sprite to the scene and for it to sit in the bottom left corner:

var groundTexture : SKTexture = SKTexture(imageNamed: "dirt-block")    
var ground : SKSpriteNode = SKSpriteNode(texture: groundTexture)
ground.position = CGPointMake(ground.size.width/2, ground.size.height/2)
self.addChild(ground)

This doesn't show anything, so I took a look at what the scene dimensions are and self.frame.size.width and self.frame.size.height are returning a width of 1024 and a height of 768, regardless of orientation.

I want this fixed in landscape mode if that makes any difference to the answer?

I'm obviously missing a very fundamental idea to do with setting up the scene, if anybody could shed any light it would be much appreciated.

Thanks.


Solution

  • You have to edit the GameViewController:

    Cut everything from viewDidLoad() except super.viewDidLoad()

    Overwrite viewWillLayoutSubviews

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
    
        if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
            // Configure the view.
            var skView = self.view as SKView
            skView.showsFPS = true
            skView.showsNodeCount = true
    
            /* Sprite Kit applies additional optimizations to improve rendering performance */
            skView.ignoresSiblingOrder = true
    
            /* Set the scale mode to scale to fit the window */
            scene.size = skView.bounds.size
            scene.scaleMode = .AspectFill
    
            skView.presentScene(scene)
        }
    }
    

    Also you should set the scene size as you can see

    scene.size = skView.bounds.size
    

    Hope this helps

    There is also a great Tutorial where this is explained better: http://www.raywenderlich.com/49721/how-to-create-a-breakout-game-using-spritekit (Chapter 1 or 2)