8
votes

Im working in a Sprite-Kit Scene right now and I want to set the Background to an image named "bgimage" for example. How would I do this programmatically through the gamescene.swift ?

import UIKit
import SpriteKit
import CoreGraphics
class gameScene: SKScene {


}
3
It is a good practice to use capitalised names for classes. Replacing gameScene with GameScene is advisable, through not necessary.Tiago Marinho

3 Answers

11
votes

You can declare your background image as an SKSpriteNode, set its position to the middle of the screen and add it to your scene.

import UIKit
import SpriteKit

class gameScene: SKScene {
    var background = SKSpriteNode(imageNamed: "bgimage")

    override func didMoveToView(view: SKView) {
        background.position = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
        addChild(background)
    }
}

Also make sure you have the image in images.xcassets.

3
votes
import UIKit
import SpriteKit
import CoreGraphics
class gameScene: SKScene {

var background = SKSpriteNode(imageNamed: "bgimage")

override func didMoveToView(to view: SKView) {
background.zPosition = 1
background.position = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)

addChild(background)


}
}

The zPosition should be lower than all the other Nodes in the gameScene

0
votes

Full-size image background

override func didMove(to view: SKView) {

    super.didMove(to:view)

    DispatchQueue.main.async{

        self.background.zPosition = 0
        self.background.position = CGPoint(x: self.size.width / 2, y: self.size.height / 2)
        self.background.size = CGSize(width: self.size.width, height: self.size.height)
        self.addChild(self.background)

    }
}