Spritekit 无尽的奔跑者 parent SKNode

Spritekit endless runner parent SKNode

我对 swift 很熟悉,但我已经开始涉足 spritekit。我一直在关注有关创建无尽跑步者的教程。作者采用的方法是创建一个包含所有 children 的单个 SKNode。然后移动此容器节点,而不是单独移动所有 child 节点。但是让我难过的是容器节点没有与之关联的大小所以我有点困惑 how/why 这有效而且作者没有真正解释它。

所以我们有

    let containerNode = SKNode()
    let thePlayer = Player("image":"player") //SKSpriteNode
    let inc = 0
    override func didMoveToView(){
        self.anchorPoint = CGPointMake(0.5,0)
        addChild(containerNode )
       containerNode.addChild(player)
         moveWorld()
    }

   func moveWorld(){
      let moveWorldAction = SKAction.moveByX(-screenWidth, y:0, duration:6)
     let block = SKAction.runBlock(movedWorld)
      let seq = SKAction.sequence([moveWorldAction,block])
      let repeatAction = SKAction.repeatActionForever(seq)
      containerNode.runAction(repeatAction)
   }

   func movedWorld() {
     inc = inc + 1
     addObjects()

   }

   func addObjects() {
   let obj = Object()
   containerNode.addChild(obj)
   let ranX = arc4random_uniform(screenWidth)
   let ranY = arc4random_uniform(screenHeight)
   obj.position = CGPointMake(screenWidth * (inc + 1) + ranX, ranY) 
   }

我在上面的代码中省略了一些从 int 到 float 的转换,但对于我想理解的观点来说这不是必需的。

我明白为什么在创建新 objects 时我们按增量做倍数,但我不明白的是 containerNode 没有大小,所以为什么要 child仁秀?这是最有效的方法吗?

我假设它只是为了方便,而不是单独移动所有其他 objects,但它没有尺寸这一事实让我感到困惑。

如果我正确理解 SKNode 的文档,这一小节应该可以回答您的问题:

Every node in a node tree provides a coordinate system to its children. After a child is added to the node tree, it is positioned inside its parent’s coordinate system by setting its position properties. A node’s coordinate system can be scaled and rotated by changing its xScale, yScale, and zRotation properties. When a node’s coordinate system is scaled or rotated, this transformation is applied both to the node’s own content and to that of its descendants. Source

同样,如果我没看错的话,当一个节点被添加到节点树时,它似乎继承了它的父坐标系。所以在这种情况下,默认情况下 containerNodeself 大小相同。

同样根据一个SKNode的frame 属性:

The frame is the smallest rectangle that contains the node’s content, taking into account the node’s xScale, yScale, and zRotation properties. Source

这又听起来像是如果未设置框架,它会采用最小的矩形(在这种情况下为 self,或者可能理解为它是 containerNode 的子项,我不确定) 因为它是自己的框架。

无论如何,它是从另一个SKNode继承的。

由于未呈现 SKNode,因此不需要(或没有)大小 属性。只有 SKNode 个可见的子类(SKLabelNodeSKShapeNode 等)需要大小(显式声明或隐式计算)。例如,SpriteKit 需要知道具有 20 x 20 纹理的 SKSpriteNode 的大小才能正确渲染它。您可以使用 SKNodecalculateAccumulatedFrame 方法来确定其节点树中所有后代(除其他 SKNode 之外)的总大小(矩形)。