Reputation: 149
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
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
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
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