Coordinate system in SpriteKit
SpriteKit coordinates
The coordinate system in Sprite Kit might give you a headache if you didn’t dig deep enough while reading the documentation.
In this post I will explain differences between SKScene
and SKNode
when it comes to coordinate system in Sprite Kit.
SKScene
Sprite Kit uses a coordinate system orientation that starts from the bottom left corner of the screen (0, 0)
, and the x
and y
values increase as you move up and to the right.
For SKScene
, the default value of the origin – anchorPoint
is (0, 0)
, which corresponds to the lower-left corner of the view’s frame rectangle. To change it to center you can specify (0.5, 0.5)
.
SKNode
The coordinate system origin in the SKNode
is defined by its anchorPoint which by default is (0.5, 0.5)
which is center of the node.
But why is it center? The texture of the sprite is drawn relative to the node position based on the anchorPoint
factor. It’s default value of (0.5, 0.5)
places the texture centered on the node’s position. You might want to adjust the anchor point, but it will change the position of the texture which you generally don’t want.
When creating a CGPath
for a physics body for your SKNode
(for example using bodyWithEdgeLoopFromPath:
method) you should use node’s coordinate system with the origin in the middle unless you changed the anchor point.
Tricks
You can set SKScene
‘s yScale
property to -1
. If you do so, everything will render upside down. Moreover, you can also set the yScale property for each SKNode
to -1
, which will cause them to render right side up.
Things to remember
-
SKNodes
have a default coordinate system where(0, 0)
is the center. -
SKScene
has a default coordinate system where(0, 0)
is the lower left corner.