如何预加载纹理图集以提高性能并减少滞后? swift,spritekit

时间:2014-11-28 03:05:22

标签: swift sprite-kit textures

我的游戏相当滞后,所以我试图通过预加载我正在使用的纹理来优化其性能。在游戏中,我使用函数向场景中添加新的精灵,因此每次调用该函数时都会创建一个新的纹理。当我移动在函数外部创建纹理的线时,我得到一个错误(参见下面的代码)。有没有人知道每次调用添加它们的函数时我怎么能避免创建纹理?

class PlayScene: SKScene, SKPhysicsContactDelegate {

  // i tried to put the "var ball..." line here but it came up as an error when contact had been made
func addBall() {


    self.physicsWorld.contactDelegate = self
    self.physicsWorld.speed = 1
    var ball = imageLoad(imageNamed: "Ball") // <--- i want to shift this out



    ball.zPosition = 1
    ball.name = "ball"

    ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width/2)
    ball.physicsBody?.dynamic = true

    ball.physicsBody?.mass = 0.01
    ball.physicsBody?.allowsRotation = true
    ball.physicsBody?.categoryBitMask = ColliderType.ballCategory.rawValue
    ball.physicsBody?.contactTestBitMask = ColliderType.heroCategory.rawValue
    ball.physicsBody?.collisionBitMask = ColliderType.heroCategory.rawValue
    ball.setScale(0.75)

    let minX = ball.size.width/2
    let maxX = self.frame.size.width - ball.size.width/2
    let rangeX = maxX - minX
    let position: CGFloat = round(CGFloat(arc4random()) % CGFloat(rangeX) + CGFloat(minX))
    acorn.position = CGPointMake(position, self.frame.size.height)
    addChild(ball)

    let minDuration = 2
    let maxDuration = 8
    let rangeDuration = maxDuration - minDuration
    let duration = Int(arc4random()) % Int(rangeDuration) + Int(minDuration)
    var actionArray:NSMutableArray = NSMutableArray()
    actionArray.addObject(SKAction.moveTo(CGPointMake(position, -acorn.size.height), duration: NSTimeInterval(duration)))

    actionArray.addObject(SKAction.removeFromParent())

    ball.runAction(SKAction.sequence(actionArray))


}

func updateWithTimeSinceLastUpdate(timeSinceLastUpdate: CFTimeInterval){
    lastYieldTimeInterval += timeSinceLastUpdate
    slowlastYieldTimeInterval += timeSinceLastUpdate
    if (lastYieldTimeInterval>1) {
        lastYieldTimeInterval = 0
        addBall()





    }
     }

1 个答案:

答案 0 :(得分:0)

我不确定imageLoad的作用,但这是预加载和重复使用纹理的一种方法。

将以下代码添加到SKScene子类

let ballTexture = SKTexture(imageNamed: "Ball")

修改你的addBall方法,通过

从纹理中创建你的球精灵
func addBall() {
    let ball = SKSpriteNode(texture: ballTexture)
    ...

我建议您创建performSelector SKAction以固定间隔添加球,而不是在update方法中添加它们。

最后,我建议您将self.physicsWorld.contactDelegate = selfself.physicsWorld.speed = 1addBall移至didMoveToView方法,这样每当您创建球时,都不会重复调用它们。< / p>