3
votes

I am creating a simple Game and I would like to get the actually size (width/height) of a SpriteKit scene to be able to present a SKNode ( / SKSpriteNode) to fill the whole display, but apparently

backgroundNode.size = CGSize(width: view.frame.width, height: view.frame.height) 

or anything similar doesn't work. The node is presented, but is just a quarter of the actually screen size.

I present the SKScene from GameViewController.swift like this:

override func viewDidLoad() {
    super.viewDidLoad()

    if let view = self.view as! SKView? {
        // Load the SKScene from 'GameScene.sks'
        let scene = GameScene(size: view.bounds.size)
        // Set the scale mode to scale to fit the window
        scene.scaleMode = .aspectFill

        // Present the scene
        view.presentScene(scene)

        view.ignoresSiblingOrder = true
    }

So how could one get the actually SpriteKit Scene size or is there another way to present an SKNode / SKSpriteNode fullscreen in a GameScene?

Update: I tried this as well:

let displaySize: CGRect = UIScreen.main.bounds
let displayWidth = displaySize.width
let displayHeight = displaySize.height

which gives me for an iPhone 8 375x667 as a size, but the Node is still displayed as a quarter of the screen.

1

1 Answers

0
votes

I created a sample project with the code below. This creates a red-colored node that fills the screen. You can use UIScreen.main.bounds and I'm using it here as a global variable. I find it helpful this way since I can access it from any code file, as I often need to use the screen size in a calculation.

GameViewController.swift

import SpriteKit
let displaySize: CGRect = UIScreen.main.bounds

class GameViewController: UIViewController {

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        let skView = self.view as! SKView
        if let scene = SKScene(fileNamed: "GameScene") {
            scene.scaleMode = .aspectFill
            scene.size = view.bounds.size
            skView.ignoresSiblingOrder = true
            skView.presentScene(scene)
        }
    }
}

GameScene.swift

import SpriteKit

class GameScene: SKScene {
    let backgroundNode = SKSpriteNode()

    override func didMove(to view: SKView) {
        backgroundNode.size = CGSize(width: displaySize.width, height: displaySize.height)
        backgroundNode.color = .red
        self.addChild(backgroundNode)
    }
}