问题描述
我正在创建一个游戏,用户可以用喷气背包控制角色.当jetpack与钻石相交时,我将钻石添加到它们的总数中,然后播放声音.但是,声音会使游戏暂停十分之一秒左右,从而中断游戏流程.这是我正在使用的代码:
I'm creating a game where the user controls a character with a jetpack. When the jetpack intersects a diamond, I add the diamond to their total and then play a sound. However, the sound makes the game pause for a tenth of a second or so and disrupts the flow. This is the code I'm using:
var diamondSound = NSBundle.mainBundle().URLForResource("diamondCollect", withExtension: "wav")!
var diamondPlayer = AVAudioPlayer?()
class GameScene: SKScene{
override func didMoveToView(view: SKView) {
do {
diamondPlayer = try AVAudioPlayer(contentsOfURL: diamondSound)
guard let player = diamondPlayer else { return }
player.prepareToPlay()
} catch let error as NSError {
print(error.description)
}
}
再后来:
override func update(currentTime: CFTimeInterval) {
if character.intersectsNode(diamond){
diamondPlayer?.play()
addDiamond()
diamond.removeFromParent()
}
}
如果那很重要的话,我也正在使用Sprite Kit.任何帮助,我们将不胜感激!
Also I am using Sprite Kit if that matters. Any help is greatly appreciated!
推荐答案
通常,我倾向于在游戏中使用SKAction.playSoundWithFile
,但这是有限制的,没有音量设置.因此,使用此扩展程序可以解决此不足:
Usually, I prefeer to use SKAction.playSoundWithFile
in my games but this one have a limitation, there is no volume setting.So, whit this extension you can solve this lack:
public extension SKAction {
public class func playSoundFileNamed(fileName: String, atVolume: Float, waitForCompletion: Bool) -> SKAction {
let nameOnly = (fileName as NSString).stringByDeletingPathExtension
let fileExt = (fileName as NSString).pathExtension
let soundPath = NSBundle.mainBundle().URLForResource(nameOnly, withExtension: fileExt)
var player: AVAudioPlayer! = AVAudioPlayer()
do { player = try AVAudioPlayer(contentsOfURL: soundPath!, fileTypeHint: nil) }
catch let error as NSError { print(error.description) }
player.volume = atVolume
let playAction: SKAction = SKAction.runBlock { () -> Void in
player.prepareToPlay()
player.play()
}
if(waitForCompletion){
let waitAction = SKAction.waitForDuration(player.duration)
let groupAction: SKAction = SKAction.group([playAction, waitAction])
return groupAction
}
return playAction
}
}
用法:
self.runAction(SKAction.playSoundFileNamed("diamondCollect.wav", atVolume:0.5, waitForCompletion: true))
这篇关于AVAudioPlayer播放时游戏滞后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!