Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to position child SKSpriteNodes inside their parents

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?

like image 710
TimurTim Avatar asked Oct 13 '15 09:10

TimurTim


1 Answers

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.

enter image description here

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)

enter image description here

More experiments of SpriteKit position and anchor point can be found here.

like image 81
WangYudong Avatar answered Oct 26 '22 22:10

WangYudong