swift - Spritekit-场景转换延迟

标签 swift sprite-kit skscene

我有一个主屏幕,上面有一个按钮,当按下这个按钮时,它应该立即转换到另一个场景,但事实并非如此。它实际上需要几秒钟。有没有办法可以预先加载该场景中的所有节点? (示例:在游戏加载屏幕中)

这是我的代码:

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 加载 SKSceneGameScene 会将您带到加载场景,加载纹理,然后在加载完成后将您移至 LevelerScene

重要的是要注意,因为对纹理的引用在 LevelerScene 中,一旦 LevelerScenedeinit 编辑,纹理将被删除从内存里。因此,如果您想返回 LevelerScene,则需要再次加载纹理。

2. 在任何 SKScene 出现之前,您可以在 GameViewController 中使用 SKTexture.preloadTextures。您需要保持对这些纹理的强烈引用(也许在单例中),然后您可以在 LevelerScene 中引用它们(或您在应用程序中需要它们的任何其他地方)。

使用这种方法,因为 SKTexture 存储在场景之外,所以当您过渡到下一个场景时,它们不会从内存中删除。这意味着如果您离开然后返回场景,则无需再次加载纹理。但是,如果您有大量纹理占用大量内存,您可能会遇到一些内存问题。

有关更多信息,请参阅 Working with Sprites 中的将纹理预加载到内存中 .

希望对您有所帮助!

关于swift - Spritekit-场景转换延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30015525/

相关文章:

ios - 基于 Swift SpriteKit 分数更改背景

ios - 将 UIButton 添加到 SKScene

swift - 在终端中运行 Swift 构建导致 "Platform Path"错误

ios - 想要对两个不同的情况使用 UIViewController 流

ios - 点击或拖动时缩放节点的功能不一致

sprite-kit - 检查 SKNode 是否正在运行 SKAction

ios - 当我进入场景时如何设置场景的缩放模式?

swift - 如何从 SKScene 呈现 UIViewController

ios - 更改 UITableViewCell 中 UIImageView 的大小

swift - 希望更好地理解 Swift 函数