LorenzoFavilla
LorenzoFavilla

Reputation: 21

Background image in gamescene.swift

What do I need to code in order to have an image (that is already in the assets.xcassets) displayed as the background of the GameScene.swift?

Upvotes: 2

Views: 343

Answers (2)

Alessandro Ornano
Alessandro Ornano

Reputation: 35372

First of all you could call you scene with the scaleMode .resizeFill that modify the SKScene's actual size to exactly match the SKView :

scene.scaleMode = .resizeFill

.resizeFill – The scene is not scaled. It is simply resized so that its fits the view. Because the scene is not scaled, the images will all remain at their original size and aspect ratio. The content will all remain relative to the scene origin (lower left).

By default, a scene’s origin is placed in the lower-left corner of the view. So, a scene is initialized with a height of 1024 and a width of 768, has the origin (0,0) in the lower-left corner, and the (1024,768) coordinate in the upper-right corner. The frame property holds (0,0)-(1024,768).The default value for the anchor point is CGPointZero (so you don't need to change it), which places it at the lower-left corner.

Finally, you can use the code below to add your background image (called of example bg.jpg):

// Set background
let txt = SKTexture(imageNamed: "bg.jpg")
let backgroundNode = SKSpriteNode(texture: txt, size:size)
self.addChild(backgroundNode)
backgroundNode.position = CGPoint(x: self.frame.midX, y: self.frame.midY)

Upvotes: 2

Sweeper
Sweeper

Reputation: 270770

Although this might not be the best way, but it's what I always do, and it works.

Assuming that you have an image that is exactly the same aize as your scene, you can do this:

// please declare bg as a class level variable
bg = SKSpriteNode(imageNamed: "name of your texture")

// the below two lines of code is my preference only. I want the
// background's anchor point to be the bottom left of the screen 
// because IMO it's easier to add other sprites as children of the background.
bg.anchorPoint = CGPoint.zero
bg.position = CGPoint(x: self.frame.width / -2, y: self.frame.height / -2)

self.addChild(bg)

Alernatively, just do this in an sks file. It's much easier.

After that, add all your game sprites as children of bg instead of self because it is easier to manage.

Upvotes: 1

Related Questions