Categories
iOS SpriteKit

Positioning a node at the edge of a screen

iOS devices have several screen sizes and aspect ratios. This is something to keep in mind when building a game in SpriteKit because placing a node at the edge of a screen is not straight forward. But first let’s take a quick look on managing scenes. One way for it is to use scene editor in Xcode for setting up all nodes in it. When scene is ready and gets presented in SKView, it is scaled based on the scaleMode property (we are looking into SKSceneScaleMode.aspectFill). Without scaling scenes it would be impossible to reuse them on iPads and iPhones. But on the other hand scaled scenes makes it a bit more tricky to position a node at the edge of a screen. For achieving that a little bit of code is needed what takes account how scene has been scaled. In the code example a SKSpriteNode is positioned at the top right of the scene with a small margin. Idea is simple: calculate a scale factor and use scaled size of the scene for positioning the node.

private var initialSize: CGSize = .zero
private var presentedSize: CGSize { return scene?.view?.bounds.size ?? size }
private var presentedScaleFactor: CGFloat { return initialSize.width / presentedSize.width }
override func sceneDidLoad()
{
super.sceneDidLoad()
initialSize = size
}
func layoutNodes()
{
let margin: CGFloat = 10
if let topRight = childNode(withName: "topRight") as? SKSpriteNode
{
topRight.position.x = presentedSize.width / 2.0 * presentedScaleFactor - topRight.size.width / 2.0 - margin
topRight.position.y = presentedSize.height / 2.0 * presentedScaleFactor - topRight.size.height / 2.0 - margin
}
}
view raw GameScene.swift hosted with ❤ by GitHub

Here is a full sample app demonstrating how to place a node to every corner and repositioning the nodes when orientation of the device changes.

Please check the sample app in GitHub: NodesAtScreenEdges.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s