嗨我是swift的新手,我的游戏是一个随机生成的方块,以随机速度下降,我的功能有问题(当用户触摸方格时执行此功能):
let Font = UIFont(name: "Avenir Next Medium", size: 16)
let bgMusicURL:NSURL = NSBundle.mainBundle().URLForResource("Destroy-Square", withExtension: "mp3")!
override func didMoveToView(view: SKView) {
do {
try SquareDestroyedSound = AVAudioPlayer(contentsOfURL: bgMusicURL, fileTypeHint: nil) }
catch _{
return print("no sound file")
}
SquareDestroyedSound.prepareToPlay()
}
func SquareExploded (pos: CGPoint, nodeColor: String, Points: String) {
let myLabel = SKLabelNode(fontNamed: Font?.fontName)
let emitterNode = SKEmitterNode(fileNamed: "ExplodedWhiteSquare.sks")
myLabel.fontSize = 20
myLabel.text = Points
myLabel.position = pos
actionMovePoint = SKAction.moveToY(pos.y + 200, duration: 0.8)
self.addChild(myLabel)
myLabel.runAction(SKAction.sequence([actionMovePoint, actionMoveDonePoint]))
emitterNode!.particleColorSequence = nil
emitterNode!.particleColorBlendFactor = 1.0
emitterNode!.particleColor = UIColor(rgba: nodeColor)
emitterNode!.particlePosition = pos
self.addChild(emitterNode!)
emitterNode!.runAction(SKAction.waitForDuration(2), completion: { emitterNode!.removeFromParent() })
SquareDestroyedSound.play()
}
这个功能需要同时做三件事:
1- myLabel是一个文本,从触摸的方形位置上升0.8秒然后应该被移除。
2 emitterNode是我创建的一个火花效果,此效果获得方形位置和颜色以产生与触摸的方块具有相同颜色的效果,此效果的持续时间为2秒然后其除去。
3- bgMusicURL / SquareDestroyedSound是触摸每个方格的声音的网址路径,它是在时间播放的
我的问题是,当用户触摸任何方格时,游戏滞后有点像屏幕冻结,fps从60降至55/52。如果我不使用此功能,该功能可以正常工作游戏不会因为没有fps下降而延迟,所以我需要帮助是否有任何方法可以优化我的代码?
答案 0 :(得分:1)
我会使用SKAction
序列来执行您的所有操作,并避免使用AVAudioPlayer
-
func SquareExploded (pos: CGPoint, nodeColor: String, Points: String) {
let myLabel = SKLabelNode(fontNamed: Font?.fontName)
let emitterNode = SKEmitterNode(fileNamed: "ExplodedWhiteSquare.sks")
myLabel.fontSize = 20
myLabel.text = Points
myLabel.position = pos
actionMovePoint = SKAction.moveToY(pos.y + 200, duration: 0.8)
self.addChild(myLabel)
myLabel.runAction(SKAction.sequence([actionMovePoint, actionMoveDonePoint]))
emitterNode!.particleColorSequence = nil
emitterNode!.particleColorBlendFactor = 1.0
emitterNode!.particleColor = UIColor(rgba: nodeColor)
emitterNode!.particlePosition = pos
self.addChild(emitterNode!)
let actionSequence=SKAction.sequence([SKAction.playSoundFileNamed("Destroy-Square.mp3", waitForCompletion: false), SKAction.waitForDuration(2),SKAction.removeFromParent()])
emitterNode!.runAction(actionSequence)
}
答案 1 :(得分:0)
我会做以下检查:
你说它会产生一个随机速度下降的随机方格?随机多少钱?如果输入预定义的方形和速度,则执行此功能 仍然制造滞后?
可以静态声明任何一个吗?如果它们需要是唯一的实例,您可以预定义一些以节省初始化时间吗?
让myLabel = SKLabelNode(fontNamed:Font?.fontName) let emitterNode = SKEmitterNode(fileNamed:" ExplodedWhiteSquare.sks") 让bgMusicURL:NSURL = NSBundle.mainBundle()。URLForResource(" Destroy-Square",withExtension:" mp3")!
类似的东西:
let emitterNode = emmitterArray.getNextInactiveEmmitter()
let bgMusicURL:NSURL = musicArray.getNextInactiveTrack()