Stack Overflow
Stack Overflow

Reputation: 149

Background Image for Sprite-Kit Scene

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 {


}

Upvotes: 11

Views: 18510

Answers (3)

Tiago Mendes
Tiago Mendes

Reputation: 5176

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)

    }
}

Upvotes: 1

user5708376
user5708376

Reputation:

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

Upvotes: 4

Daniel Mihaila
Daniel Mihaila

Reputation: 585

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.

Upvotes: 13

Related Questions