Spritekit - 从另一个场景转换时,在 .sks 文件中创建的场景为空白

Spritekit - Scene created in .sks file is blank when transitioning from another scene

我有一个主菜单场景,当按下一个按钮时,它应该转换到另一个场景。它似乎可以正确过渡,但是当它完成过渡时,第二个场景是空白的。我在第二个场景的 didMove 函数中放置了断点,它似乎是正确的 运行 。我知道当直接从 GameViewController 打开时,第二个场景可以正常工作。我不确定为什么从另一个场景过渡时它是空白的。这是我当前的代码:

class StartScene: SKScene {

  var playButton = SKSpriteNode()
  let playButtonTex = SKTexture(imageNamed: "BlueRoundedButton")

  override func didMove(to view: SKView) {

    playButton = SKSpriteNode(texture: playButtonTex)
    playButton.size = CGSize(width: 200, height: 50)
    playButton.position = CGPoint(x: frame.midX, y: frame.midY)
    self.addChild(playButton)
  }

  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
      let pos = touch.location(in: self)
      let node = self.atPoint(pos)

      if node == playButton {
        if let view = view {
          let transition:SKTransition = SKTransition.fade(withDuration: 1)
          let scene:SKScene = PoolScene(size: self.size)
          self.view?.presentScene(scene, transition: transition)
        }
      }
    }
  }
}

这是过渡到的场景:

class PoolScene: SKScene, SKPhysicsContactDelegate {

  var ballPoke : SKSpriteNode?
  var ballBlue : SKSpriteNode?
  var ballOrange : SKSpriteNode?


  override func didMove(to view: SKView) {

    let borderBody = SKPhysicsBody(edgeLoopFrom: self.frame)
    borderBody.friction = 0
    self.physicsBody = borderBody

    self.physicsWorld.gravity = CGVector(dx: 0, dy: 0)
    physicsWorld.contactDelegate = self

    ballBlue = childNode(withName: blueBallName) as? SKSpriteNode
    ballOrange = childNode(withName: orangeBallName) as? SKSpriteNode
    ballPoke = childNode(withName: pokeBallName) as? SKSpriteNode


    ballBlue?.physicsBody?.categoryBitMask = blueBallCategory
    ballOrange?.physicsBody?.categoryBitMask = orangeBallCategory
    ballPoke?.physicsBody?.categoryBitMask = pokeBallCategory
    borderBody.categoryBitMask = borderCategory


  }

您调用了错误的 init 方法来加载您的 PoolScene。你这样做的方式是在你不使用 Xcode 视觉关卡编辑器的时候。 与您的 GameViewController 一样,您需要使用对相应 .sks 文件的引用来初始化场景。

 if node == playButton {
     if let view = view {
        let transition = SKTransition.fade(withDuration: 1)

         if let scene = PoolScene(fileNamed: "PoolScene") {
              view.presentScene(scene, transition: transition)
         }
      }
  }

或者更简洁的方式

  if node == playButton {
     let transition = SKTransition.fade(withDuration: 1)

     if let scene = PoolScene(fileNamed: "PoolScene") {
         view?.presentScene(scene, transition: transition)    
      }
  }

"fileNamed:..." 是您的 PoolScene 的 .sks 文件的名称,您通常将其命名为与 .swift 文件完全相同的名称。使用 guard 或 if let 因为它将 return 一个可选的。

作为一个小提示,使用 swifts 类型推断让您的代码更漂亮一些,就像我的示例中那样。

希望对您有所帮助