【问题标题】:how to preload texture atlas to improve performance and reduce lagging? swift, spritekit如何预加载纹理图集以提高性能并减少滞后?迅捷,精灵包
【发布时间】:2014-11-28 03:05:22
【问题描述】:

我的游戏有点滞后,所以我试图通过预加载我正在使用的纹理来优化它的性能。在游戏中,我使用函数将新精灵添加到场景中,因此每次调用该函数时都会创建一个新纹理。当我将创建纹理的线移到函数之外时,出现错误(请参见下面的代码)。有谁知道每次调用添加纹理的函数时如何避免创建纹理?

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()





    }
     }

【问题讨论】:

    标签: swift sprite-kit textures


    【解决方案1】:

    我不确定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 方法,这样就不会在创建球时重复调用它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-21
      • 2022-10-04
      • 1970-01-01
      相关资源
      最近更新 更多