我的游戏相当滞后,所以我试图通过预加载我正在使用的纹理来优化其性能。在游戏中,我使用函数向场景中添加新的精灵,因此每次调用该函数时都会创建一个新的纹理。当我移动在函数外部创建纹理的线时,我得到一个错误(参见下面的代码)。有没有人知道每次调用添加它们的函数时我怎么能避免创建纹理?
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()
}
}
答案 0 :(得分:0)
我不确定imageLoad
的作用,但这是预加载和重复使用纹理的一种方法。
将以下代码添加到SKScene子类
let ballTexture = SKTexture(imageNamed: "Ball")
修改你的addBall
方法,通过
func addBall() {
let ball = SKSpriteNode(texture: ballTexture)
...
我建议您创建performSelector
SKAction
以固定间隔添加球,而不是在update
方法中添加它们。
最后,我建议您将self.physicsWorld.contactDelegate = self
和self.physicsWorld.speed = 1
从addBall
移至didMoveToView
方法,这样每当您创建球时,都不会重复调用它们。< / p>