为什么我的声音使我的游戏落后于Swift Spritekit? [英] Why is my sound making my game lag in Swift Spritekit?

查看:74
本文介绍了为什么我的声音使我的游戏落后于Swift Spritekit?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的英雄节点收集一个硬币并且我的游戏中有一个小小的打I时,我就有这种声音效果.当收集硬币时涉及声音时,它不像其他游戏中那样平滑.我究竟做错了什么?这是我的声音代码:

I have this sound effect when my hero node collects a coin and there is this small hiccup in my game. Its not smooth like in other games when there is sound involved when collecting a coin. What am I doing wrong? Heres my code for the sound:

  class GameScene: SKScene, SKPhysicsContactDelegate {

   var coinSound =  NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("coin", ofType: "wav")!)
   var coinAudioPlayer = AVAudioPlayer()

   override func didMoveToView(view: SKView) {

   coinAudioPlayer = AVAudioPlayer(contentsOfURL: coinSound, error: nil)
   coinAudioPlayer.pause()
   }

   if firstBody.categoryBitMask == HeroCategory && secondBody.categoryBitMask == CoinCategory {

   coinAudioPlayer.prepareToPlay()
   coinAudioPlayer.play()
   coinAudioPlayer.currentTime = NSTimeInterval(1.0)
    }

推荐答案

使用

Use SKAction.playSoundFileNamed. When you create an SKAction instance ahead of time, it does all the necessary prep to perform the action (in this case, playing a sound) without lag during gameplay. To run the action (play the sound), call runAction on a node — this can be any node, even the scene itself.

由于您将哪个节点用于声音目的并不重要,因此请使用最方便的那个节点.例如,如果您只是播放声音,则可以在场景中调用runAction.但是,如果您的声音属于某个动作组或序列(例如,将一个精灵动画化)的一部分,则可以使声音动作成为该序列的一部分,并在要制作动画的精灵上播放.

Since it doesn't matter which node you use for sound purposes, use whichever is most convenient. For example, if you're just playing a sound you might call runAction on the scene. But if your sound is part of an action group or sequence that, say, animates a sprite, you could make the sound action part of that sequence and play it on the sprite that you're animating.

请参见

See SpriteKit Programming Guide for more about actions.

不相关的Swift提示:对于不变的引用,请使用let而不是var.它可以帮助您避免以后引入错误,还可以帮助编译器优化代码.

Unrelated Swift tip: use let instead of var for references that won't change. It can help keep you from introducing bugs later, and it probably helps the compiler optimize your code, too.

这篇关于为什么我的声音使我的游戏落后于Swift Spritekit?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆