I don't really understand the logic of positioning child nodes. Lets say I have a rectangle. And if I haven't changed its anchor point, child node will appear exactly in the middle by default. But how to position it on the upper-left edge of rectangle for example? Or down-right? I tried
child.zPosition = 1
child.position.y = rect.size.height / 2
rect.addChild(child)
But it is not positioned in the middle by Y axis. It's somewhere on top. What instruments should I use to position child nodes regarding/inside their parents?
The default anchor point in SpriteKit is (0.5, 0.5), which is the center of a node/sprite. (0, 0) is bottom left corner and (1, 1) is top right corner. Look at this picture.
After choosing a node's anchor point, you can treat it as the origin of a coordinate system whose range is the node's frame size. The position offset is calculated/affected by both the child's anchor point and its parent's anchor point.
For example, a (red) parent node rect
is (100, 100) in size and a (green) child node child
is (50, 50) in size. Set the child position at (-25, 25) in parent's coordinate system will have the following result.
// parent node
let parent = SKSpriteNode(color: UIColor.redColor(), size: CGSizeMake(100.0, 100.0))
parent.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame));
self.addChild(parent)
// child node
let child = SKSpriteNode(color: UIColor.greenColor(), size: CGSizeMake(50.0, 50.0))
child.zPosition = 1
child.position = CGPointMake(-parent.size.width/4, parent.size.height/4) // (-25, 25))
parent.addChild(child)
More experiments of SpriteKit position and anchor point can be found here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With