How to position child SKSpriteNodes inside their parents

北城以北 提交于 2019-12-09 11:36:37

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/33099051/how-to-position-child-skspritenodes-inside-their-parents

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!