【问题标题】:Add SKShapeNode in another one在另一个中添加 SKShapeNode
【发布时间】:2015-06-15 12:45:07
【问题描述】:

我想在另一个正方形中画一个正方形;但我不能以正确的方式定位第二个。 我可以根据第一个平方坐标进行定位吗?

    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)

【问题讨论】:

    标签: swift sprite-kit skshapenode


    【解决方案1】:

    您应该改用 SKSpriteNode。这样您就可以轻松添加它,而无需手动设置位置。因为在一个 SKSpriteNode 中,中心始终是节点的中心:

    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)
    

    【讨论】:

    • 圈子呢?如果我想画圆形而不是正方形,我该怎么办?
    【解决方案2】:

    节点的位置是相对于其父位置的。 如果您希望 tile 节点位于其父节点的中心,则将其位置设置为:

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

    这会将图块放置在tileBackground 节点的中心。 另请注意,您不需要更新磁贴位置以“跟随”tileBackground 节点。更新tileBackground 位置将自动将磁贴保持在其中心

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多