11

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 {


}
Stack Overflow
  • 149
  • 1
  • 1
  • 7
  • 3
    It is a good practice to use capitalised names for classes. Replacing `gameScene` with `GameScene` is advisable, through not necessary. – Tiago Marinho Jul 09 '15 at 03:15

3 Answers3

13

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.

Parth Sane
  • 587
  • 7
  • 24
Daniel Mihaila
  • 585
  • 1
  • 6
  • 13
4
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

  • Swift 4 syntax change `override func didMove(to view: SKView) {` Also, thanks for the hint on the zPosition. – Canuk Apr 12 '18 at 18:23
1

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)

    }
}
Tiago Mendes
  • 4,572
  • 1
  • 29
  • 35