Logo for tanaschita.com

How to position and size SpriteKit nodes

Learn how positioning and sizing works in SpriteKit

27 Dec 2021 · 3 min read

When adding a SpriteKit scene to a view or adding nodes to a scene, configuring the correct sizes and positions may not be intuitive at first. This quick tip explains methods and properties we can use to achieve the desired result.

Scene's scaleMode property

When creating a scene, we can initialize it with a fixed size or set it through its size property.

let scene = SnowScene(size: CGSize(width: 300, height: 400))

Sometimes, a fixed size is exactly what we want. In other cases, we want the scene to size accordingly to its containing view. For those cases, the scaleMode property comes in handy.

let scene = SnowScene()
scene.scaleMode = .resizeFill
Sponsorship logo
Join the FREE iOS Architect Crash Course (for a limited time!)
If you’re a mid/senior iOS developer who’s looking to improve both your skills and salary level, then join this 100% free online crash course. Hurry up because it's available only until November 27th!
Click to get it now

By setting it to resizeFill, SpriteKit will automatically resize the scene so that it always matches the view’s size.

You can check out more scale mode options in the official documentation.

Overriding didChangeSize(:)

To be able to accordingly adjust positions and sizes of the nodes when the scene's size changes, we can override the didChangeSize(:) method in our scene.

class CircleScene: SKScene {
let circleNode = SKShapeNode(circleOfRadius: 100)
override func didMove(to view: SKView) {
addChild(circleNode)
}
override func didChangeSize(_ oldSize: CGSize) {
circleNode.position = CGPoint(x: size.width/2, y: size.height - circleNode.frame.size.height / 2)
}
}

Important to know here is, that the scene's anchor point is at the bottom left corner while the node's anchor point is at the center.

Different positions of a node in a scene
Different positions of a node in a scene

When it comes to positioning emitter nodes as we did in this article on creating a particles snow effect with SpriteKit and SwiftUI, instead of setting the position property, we set the particlePosition and particlePositionRange to position the node accordingly.

Sponsorship logo
Join the FREE iOS Architect Crash Course (for a limited time!)
If you’re a mid/senior iOS developer who’s looking to improve both your skills and salary level, then join this 100% free online crash course. Hurry up because it's available only until November 27th!
Click to get it now

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

spritekit

swiftui

swift

ios

Creating a particles snow effect with SpriteKit and SwiftUI

In this Christmas special, we'll have some fun with snow particles.

20 Dec 2021 · 5 min read

Latest articles and tips

© 2022 tanaschita.com

Privacy policy

Impressum