How to place SKSpriteNodes subsidiaries inside your parents

I really don't understand the logic of positioning child nodes. Let's say I have a rectangle. And if I have not changed my anchor point, the child of the node will be displayed exactly in the middle by default. But how to place it on the upper left edge of the rectangle, for example? Or go down? I tried

child.zPosition = 1 child.position.y = rect.size.height / 2 rect.addChild(child) 

But it is not located in the middle of the Y axis. It is somewhere above. What tools should be used to place child nodes relative to / inside their parents?

+5
source share
1 answer

The default binding core in SpriteKit is (0.5, 0.5), which is the center of the node / sprite. (0, 0) is the lower left corner and (1, 1) is the upper right corner. Check out this image .

enter image description here

After selecting the node of the node point, you can consider it as the origin of the coordinate system, the range is the node of the frame size. The position offset is calculated / depends on both the child anchor point and its parent anchor point.

For example, the (red) parent node rect has a size (100, 100) and has the (green) child node node size (50, 50). Set the child position to (-25, 25) in the parent coordinate system, will have the following result.

 // parent node let rect = SKSpriteNode(color: UIColor.redColor(), size: CGSizeMake(100.0, 100.0)) rect.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame)); self.addChild(rect) // child node let child = SKSpriteNode(color: UIColor.greenColor(), size: CGSizeMake(50.0, 50.0)) child.zPosition = 1 child.position = CGPointMake(-rect.size.width/4, rect.size.height/4) // (-25, 25)) rect.addChild(child) 

enter image description here

Other experiments with SpriteKit positions and anchor points can be found.

+16
source

Source: https://habr.com/ru/post/1233596/


All Articles