我有一个主屏幕,上面有一个按钮,当按下这个按钮时,它应该立即转换到另一个场景,但事实并非如此。它实际上需要几秒钟。有没有办法可以预先加载该场景中的所有节点? (示例:在游戏加载屏幕中)
这是我的代码:
let pressButton = SKAction.setTexture(SKTexture(imageNamed: "playButtonP.png"))
let buttonPressed = SKAction.waitForDuration(0.15)
let buttonNormal = SKAction.setTexture(SKTexture(imageNamed: "playButton.png"))
let gameTrans = SKAction.runBlock(){
let doors = SKTransition.doorsOpenHorizontalWithDuration(0)
let levelerScene = LevelerScene(fileNamed: "LevelerScene")
self.view?.presentScene(levelerScene, transition: doors)
}
playButton.runAction(SKAction.sequence([pressButton,buttonPressed,buttonNormal,gameTrans]))
最佳答案
您可以在呈现场景之前预加载您在 LevelerScene
中使用的 SKTexture
。然后,一旦加载完成,您就可以呈现场景。这是 Apple 文档中的一个示例,已翻译成 Swift:
SKTexture.preloadTextures(arrayOfYourTextures) {
if let scene = GameScene(fileNamed: "GameScene") {
let skView = self.view as! SKView
skView.presentScene(scene)
}
}
在您的情况下,您有几个选择:
1.
保留一个纹理数组,您需要在 LevelerScene
中使用这些纹理,并在 GameScene
中预加载:
class LevelerScene : SKScene {
// You need to keep a strong reference to your textures to keep
// them in memory after they've been loaded.
let textures = [SKTexture(imageNamed: "Tex1"), SKTexture(imageNamed: "Tex1")]
// You could now reference the texture you want using the array.
//...
}
现在在 GameScene
中,当用户按下按钮时:
if let view = self.view {
let leveler = LevelerScene(fileNamed: "LevelerScene")
SKTexture.preloadTextures(leveler.textures) {
// Done loading!
view.presentScene(leveler)
}
}
没有办法绕过等待一段时间,但采用这种方法主线程不会被阻塞,您将能够与 GameScene
交互,同时 LevelerScene
正在加载。
您也可以使用这种方法为 LevelerScene
加载 SKScene
。 GameScene
会将您带到加载场景,加载纹理,然后在加载完成后将您移至 LevelerScene
。
重要的是要注意,因为对纹理的引用在 LevelerScene
中,一旦 LevelerScene
被 deinit
编辑,纹理将被删除从内存里。因此,如果您想返回 LevelerScene
,则需要再次加载纹理。
2. 在任何 SKScene
出现之前,您可以在 GameViewController
中使用 SKTexture.preloadTextures
。您需要保持对这些纹理的强烈引用(也许在单例中),然后您可以在 LevelerScene
中引用它们(或您在应用程序中需要它们的任何其他地方)。
使用这种方法,因为 SKTexture
存储在场景之外,所以当您过渡到下一个场景时,它们不会从内存中删除。这意味着如果您离开然后返回场景,则无需再次加载纹理。但是,如果您有大量纹理占用大量内存,您可能会遇到一些内存问题。
有关更多信息,请参阅 Working with Sprites 中的将纹理预加载到内存中 .
希望对您有所帮助!
关于swift - Spritekit-场景转换延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30015525/