预加载后的SpriteKit场景转换延迟和帧速率下降

时间:2016-08-13 16:37:22

标签: ios swift debugging sprite-kit frame-rate

我正在使用SpriteKit构建一个游戏,并且最近遇到了问题,我的帧速率从GameScene开始不断地从60降至50-45,从GameScene打开StartScene后延迟几秒我的GameScene。我已经尝试了很多不同的东西,我相信我的一个主要问题与设置非常频繁产生的SKSpriteNode子类的动画有关,当我停止动画它们而不是使用单个纹理时帧速率保持在60.我之前{ {3}}关于将纹理预加载到SpriteKit中,并收到了很棒的答案,但我可能还没有完全理解。此时我将所有GameScene纹理放在一个Atlas中,然后通过在//Preload textures of GameScene before running it let alienTexture1 = SKTextureAtlas(named:"Sprites").textureNamed("alienTexture1") let alienTexture2 = SKTextureAtlas(named:"Sprites").textureNamed("alienTexture2") ... class GameScene: SKScene, SKPhysicsContactDelegate { 之前为每个纹理创建常量来加载它们:

SKTextureAtlas(named: "YourTextureAtlasName").preloadWithCompletionHandler { 
// Now everything you put into the texture atlas has been loaded in memory
}

我知道我应该使用:

let alienTexture1 = SKTextureAtlas(named:"Sprites").textureNamed("alienTexture1")

预加载纹理,但我不确定括号之间是什么,以及应该调用类似init的行。然后在我所拥有的一些Alien SKSpriteNode子类的GameScene内部调用这些纹理。我不明白,因为预载明显不能正常工作。我也不确定在切换到let时如何处理延迟,但我想这也与我在开始时使用所有lstResults.DisplayMember = "Word"; 语句加载纹理的方式有关。任何建议都会很棒。

我已经看过关于这个问题的其他问题,并认为这是特定的,不是重复。

1 个答案:

答案 0 :(得分:0)

我也对此感到困惑,我绝不是专家,但基本上预加载纹理只是意味着你将它们存储在一个不会被释放的数组/属性中。

我真的不使用SKTextureAtlas("")。preloadWithCompletionHandler方法。我相信这个想法基本相同。

例如,您可以创建静态纹理加载类

 class Textures {

      static var alien1 = [SKTexture]() // array off all alien 1 textures


      static func preloadAll() {
           loadAlien1()
           ...
      }

      // Alien 1
      static func loadAlien1() {

           // Get atlas
           let alien1AtlasName = "Your atlas name"
           let alien1Atlas = SKTextureAtlas(named: alien1AtlasName)

            // Loop through images in atlas and append to alienTexture property
           // In this case there is 2 images in the atlas)
           // Images should be appended by _1 , _2 etc 
           for image in 1...2 {
               let textureName = "\(alien1AtlasName)_\(image)"
               let texture = alien1Atlas.textureNamed(textureName)
               alien1.append(texture)
           }   
      }
 }

当您的应用在appDelegate或GameViewController中启动时预加载纹理

 Textures.preloadAll()

如果你有很多纹理并且想要保持较低的内存使用率,只需预先加载你最初需要的纹理,然后为其他级别加载其他纹理。

  Texture.loadAlien1()

你可以在你的子类或SKScene中对你的外星人1个角色运行动画

let textureAnimation = SKAction.animateWithTextures(Textures.alien1, timePerFrame: 0.3)
alien1Sprite.runAction(SKAction.repeatActionForever(textureAnimation), withKey: "Alien1AnimationKey")

如果您需要清理纹理,请不再需要它们,或者如果您的应用程序获得内存不足警告,您只需清空阵列。

 Textures.alien1.removeAll()

关于性能,您还应将地图集存储在xCode资产目录中,这是xCode 7中的新功能,而不是项目中的文件夹。

希望这有帮助