Add SKShapeNode in another one

459 views Asked by At

I want to draw a square in another square; but I can't position the second one in the right way. What can I do for positioning based on first square coordinates?

    var tileBackground = SKShapeNode(rectOfSize: CGSize(width: screenWidth, height: screenWidth))
    tileBackground.name = "tileBackground"
    tileBackground.fillColor = SKColor.whiteColor()
    tileBackground.position = CGPoint(x: frame.midX, y: frame.midY);
    self.addChild(tileBackground)

    var tile = SKShapeNode(rectOfSize: CGSize(width: tileSize, height: tileSize))
    tile.name = "tile1"
    tile.fillColor = SKColor.redColor()
    tile.position = CGPointMake(100,100)
    tileBackground.addChild(tile)
2

There are 2 answers

1
Christian On BEST ANSWER

You should use SKSpriteNode instead. That way you can add it easily and without setting the position manually. Because in an SKSpriteNode, the center is always the center of the node:

var tileBackground = SKSpriteNode(color: UIColor.whiteColor(), size: CGSizeMake(width: screenWidth, height: screenWidth))
tileBackground.name = "tileBackground"
tileBackground.position = CGPoint(x: frame.midX, y: frame.midY);
self.addChild(tileBackground)


var tile = SKSpriteNode(color: UIColor.redColor(), size: CGSize(width: tileSize, height: tileSize))
tile.name = "tile1"
tileBackground.addChild(tile)
0
giorashc On

A node's position is relative to its parent position. If you want the tile node to be in the center of its parent then set its position as:

tile.position = CGPoint(x: tileBackground.size.width / 2.0, y: tileBackground.size.height / 2.0)

which will place the tile in center of the tileBackground node. also note that you do not need to update the tile position to "follow" the tileBackground node. Updating the tileBackground position will automatically keep the tile in its center