Stephen Haney

SKSpriteNodes anchorPoint in Swift and SpriteKit

Note: This is a free excerpt from my new book, Game Development with Swift. If you like this post, you’ll love the book! The book walks you through the creation of a 2D iOS game from start to publication on the App Store. So far, I’ve received nothing but great feedback from readers. Check out my new Swift SpriteKit book on Amazon

SpriteKit uses a grid of points to position nodes. In this grid, the bottom left corner of the scene is (0,0), with a positive X-axis to the right and a positive Y-axis to the top. Similarly, on the individual sprite level, (0,0) refers to the bottom left corner of the sprite, while (1,1) refers to the top right corner.

Alignment with Anchor Points

Each sprite has an anchor point property, or an origin. The anchorPoint property allows you to choose which part of the sprite aligns to the sprite’s overall position.

The default anchor point is (0.5,0.5), so new SKSpriteNodes center perfectly on their position.

Keep Game Sprites Organized by
Extending SKSpriteNode with a Wrapper Class

Xcode Project and Game Organization

Even a simple game can quickly explode into a rats nest if we don’t adhere to structure from the start. I’ve learned that it’s very helpful to create a Sprite class that wraps SKSpriteNode. You can extend this class with custom functions (I’ll detail creating a ‘touch’ event handler for sprites next post), and inherit down into other classes that share basic Sprite functions like enemies, the player class, and NPCs.

Positioning SKSprites in SpriteKit with
SKScene scaleMode

I quickly ran into a snag upon firing up a new Xcode SpriteKit project and attaching a few test SKSpriteNodes to my SKScene. None of my dummy sprites were showing up at the size or location I anticipated! After a bit of web searching I realized that SKScenes are automatically scaled based on the screen size of the device. I can see how this is pretty handy, but it’s the kind of thing I like to make sure I get right early in the dev process. Here’s how I created a consistent positioning and sizing system I can trust.