在spriteKit Swift4中从父节点删除子节点时出错

时间:2018-11-29 00:57:46

标签: xcode swift3 sprite-kit

我制作了视差背景,在GameScene.sks中,我添加了一个空节点,并向一个空节点添加了两个精灵。我有一个重置按钮,当我单击它时,我需要将背景删除并添加到它的位置(重新启动),但是当我在scrollBg.removeAllChildren重新启动函数中添加时,会发生错误,我该如何正确地从中添加和删除子项现场?

  import SpriteKit
  import GameplayKit



class GameScene: SKScene {

     var player: SKSpriteNode!
     var scrollBg: SKNode!
     var spawnTimer: CFTimeInterval = 0
     let fixedDelta: CFTimeInterval = 1.0/60.0 /* 60 FPS */
     let scrollSpeed: CGFloat = 700
     var sinceTouch: CFTimeInterval = 0


       func resetGameScene() {

        scrollBG.removeAllChildren()
        player.removeAllChildren()
        player.position = CGPoint(x: 590 , y: 690)

        pauseButton()

      }

      override func didMove(to view: SKView) {

        physicsWorld.contactDelegate = self
        player = childNode(withName: "player") as? SKSpriteNode
        scrollBg = childNode(withName: "scrollBG")!

        resetGameScene()
      }


       func scrollWorld() {

         scrollBg.position.y -= scrollSpeed * CGFloat(fixedDelta)

           for ground in scrollBg.children as! [SKSpriteNode] {

         let groundPosition = scrollBg.convert(ground.position, to: 
                                                             self)

            if groundPosition.y <= -ground.size.width  {
               let newPosition = CGPoint(x: groundPosition.x, y: 
                   (self.size.width ) + ground.size.width * 2)

              ground.position = self.convert(newPosition, to: 
                                                          scrollBg)
               }
            }
         }



       override func update(_ currentTime: TimeInterval) {

           sinceTouch+=fixedDelta
           spawnTimer+=fixedDelta
           scrollWorld()
           }







       }

0 个答案:

没有答案