I am making a sprite kit game and I am using the plist file to set properties of each level. One of the properties in my plist file is a dictionary called patterns, which contains n items, where each of the items is a block, with hand typed x and y positions. This model is working perfectly fine for the kind of game I am making, as it is very convenient to set the levels right in a quick manner. However, I am facing one drawback I cant solve myself due to the lack of coding experience: some of the levels have as many as 290 blocks, so when the app tries to read the level, the app freezes for like 5 seconds. This is very annoying for the user. At the beginning my approach was: Read the plist file, and for each item call the method which creates the block as a SKSpriteNode using its imageNamed "" method. I thought this is the reason it lags so much, the fact that I am trying to load 300 sprites at the runtime seemed as a promising cause of the problem. Then I tried the following: I made the method which loads a pool of block initially, when the game starts for the first time. This is my method for that
func addObsticles1ToPool() {
for i in 0...300 {
let element = SKSpriteNode(imageNamed: "obsticle1")
element.hidden = true
obsticle1Pool.append(element)
}
}
Then, my code reads the plist file, and for each of the block calls the following:
func block(x: CGFloat, y: CGFloat, movingUp: Bool, movingSide: Bool, spin: Bool, type: Int16) {
var block: SKSpriteNode!
for obs in obsticle1Pool {
if obs.hidden {
block = obs
break
}
}
block.hidden = false
// Further down the properties of the block are set, such as actions it should perform depending on the input values, also its physics body is set.
I also have methods handling the fact that new elements should be added to the pool as game the proceeds and all that works just fine. The lag time dropped to around 3.5 - 4 secs, but that is still not good enough obviously. I would like to have a game with no lag. However, I am not sure if there is another, more efficient way, to do what I am trying to do than using the sprites pool. Does anyone know how to reduce this lag time?
答案 0 :(得分:6)
我遇到了同样的问题!问题出在这一行......
let element = SKSpriteNode(imageNamed: "obsticle1")
SpriteKit不够聪明,不知道已经使用该图像创建了纹理。所以它正在做的是一遍又一遍地创建纹理,这是昂贵的。
首先在循环外部创建纹理,然后使用纹理创建精灵节点。像这样......
let elementTexture = SKTexture(imageNamed: "objstical1")
for i in 0...300 {
let element = SKSpriteNode(texture: elementTexture)
element.hidden = true
obsticle1Pool.append(element)
}
这不仅会快一点,而且会减少你的应用程序内存...假设它与我遇到的问题相同。希望这会有所帮助。