我正在 iOS Swift 中设计一款游戏。
我有一个大约 100 个 1920x1080p PNG 的大型纹理图集。当我调用这些函数时,由于内存压力,它使应用程序崩溃。当我禁用该功能时,我的应用程序运行正常。
我可以通过编辑我的代码来防止这种崩溃吗?还是我的纹理图集太大了?
代码:
var waterWave: SKSpriteNode!
var waterWalkingFrames : [SKTexture]!
func addWater() {
let waterAnimatedAtlas = SKTextureAtlas(named: "water.atlas")
var waterFrames = [SKTexture]()
let numImages = waterAnimatedAtlas.textureNames.count
for var i=0; i<numImages; i++ {
let waterTextureName = "water_000\(i)"
waterFrames.append(waterAnimatedAtlas.textureNamed(waterTextureName))
}
self.waterWalkingFrames = waterFrames
let firstFrame = waterWalkingFrames[0]
self.water = SKSpriteNode(texture: firstFrame)
self.water.anchorPoint = CGPointMake(0.5, 0.5)
self.water.position = CGPointMake(CGRectGetMidX(self.frame), self.runningBar.position.y + (self.runningBar.size.height / 2) + 5)
self.water.size.width = self.frame.size.width
self.water.size.height = self.frame.size.height
self.water.zPosition = 7
self.addChild(self.water)
waterAnimation()
}
func waterAnimation() {
self.water.runAction(SKAction.repeatActionForever(
SKAction.animateWithTextures(waterWalkingFrames, timePerFrame: (1 / 60), resize: false, restore: true)), withKey:"surferBasic")
}
最佳答案
即使您以某种方式优化纹理(例如 changing texture format ),这样的动画也总是很昂贵。如果使用标准 RGBA8888 格式存储在 RAM 内存中时,1920x1080px 纹理占用大约 8 兆字节,如您所说,因为 device memory limitation ,应用程序有时会崩溃。
在这种情况下,如果您的动画允许您这样做,一个好的方法是制作视频,然后使用SKVideoNode。播放它。这甚至在文档中被推荐,因为在某些情况下使用纹理可能很昂贵:
Like any other node, you can put the movie node anywhere inside the node tree and Sprite Kit will render it properly. For example, you might use a video node to animate some visual behaviors that would be expensive to define using a collection of textures.
这将是一种适合背景动画、剪辑场景、介绍......
要循环播放视频,您可以使用 AVPlayer 到 initialize SKVideoNode with it .阅读更多 here .我建议你这样做,因为 SKVideoNode 仅限于控制视频播放的 play() 和 pause() 方法。
希望这对您有所帮助并有所帮助!
关于ios - 大型纹理图集因内存压力而导致终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30555313/