2016-08-13 64 views
1

我在SpriteKit中構建了一個遊戲,並且最近遇到了問題,我的幀速率不斷從60開始下降到50-45,僅在GameScene和打開GameScene from我的StartScene。我嘗試了一堆不同的東西,我相信我的一個主要問題是與動畫生成頻繁產生的SKSpriteNode子類有關,當我停止對它們進行動畫製作並使用單個紋理時,幀速率保持在60.我之前爲posted關於將紋理預加載到SpriteKit中,並收到真棒答案,但我可能還沒有完全理解。在這一點上我有我所有的GameScene紋理單一Atlas和我通過之前我GameScene創造的每一項權利常數加載它們都在:SpriteKit現場轉換滯後和預加載後的幀速下降

//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")這樣的行應該被調用時會發生什麼。這些紋理然後在我有的一些Alien SKSpriteNode子類的init中被調用。我不理解某些東西,因爲預加載顯然無法正常工作。我也不確定在切換到GameScene時如何處理延遲,但我想這也與我在開始時加載紋理的方式有關,其中包括所有這些let聲明。任何建議都會很棒。

我看過關於這個問題的其他問題,並覺得這是足夠具體,它不是重複。

回答

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這樣

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

運行在您的外星人1個字符動畫如果您需要清潔的紋理,櫃面你不再需要它們,或者如果你的應用程序得到低內存警告你只需清空數組。

Textures.alien1.removeAll() 

在性能有關的,你也應該存儲在Xcode資產目錄,這是在Xcode 7中的新功能,在您的項目文件夾,而不是你的地圖集。

希望這會有所幫助