我是 Swift 编码的新手,并试图弄清楚如何在触摸 Node.js 时使用开/关功能制作循环音频。我认为实现它的最佳方法是通过 SKAudioNode,但我不确定我在以下代码中做错了什么。在节点上按下时 - SKAudioNode 开始播放,然后在按下关闭声音后 - 声音不会停止。再次按下时 - 声音与前一次重叠。把整个重要的部分放在这里。先感谢您。
import SpriteKit
import AVFoundation
我在这里创建一个布尔值来触发声音是打开还是关闭:
var firesoundon = false
接下来设置场景。
class GameScene2: SKScene {
override func didMoveToView(view: SKView) {
setUpScenery()
}
private func setUpScenery() {
//BACKGROUND
let background = SKSpriteNode(imageNamed: backgroundImage, normalMapped: true)
background.anchorPoint = CGPointMake(0, 0)
background.position = CGPointMake(0, 0)
background.zPosition = Layer.ZBackground
background.size = CGSize(width: self.view!.bounds.size.width, height: self.view!.bounds.size.height)
background.lightingBitMask = 1;
addChild(background)
//FIRE
let fireLayerTexture = SKTexture(imageNamed: fireImage)
let fireLayer = SKSpriteNode(texture: fireLayerTexture)
fireLayer.anchorPoint = CGPointMake(1, 0)
fireLayer.position = CGPointMake(size.width, 0)
fireLayer.zPosition = Layer.Z4st
addChild(fireLayer)
let firePath = UIBezierPath()
firePath.moveToPoint(CGPointMake(0, 0))
firePath.addCurveToPoint(CGPointMake(115, 215), controlPoint1: CGPointMake(5, 170), controlPoint2: CGPointMake(90, 190))
firePath.addCurveToPoint(CGPointMake(150, 260), controlPoint1: CGPointMake(115, 215), controlPoint2: CGPointMake(120, 295)) //curve1
firePath.addCurveToPoint(CGPointMake(180, 280), controlPoint1: CGPointMake(150, 260), controlPoint2: CGPointMake(155, 350)) //curve2
firePath.addCurveToPoint(CGPointMake(225, 280), controlPoint1: CGPointMake(180, 280), controlPoint2: CGPointMake(210, 395)) //curve3
firePath.addCurveToPoint(CGPointMake(250, 260), controlPoint1: CGPointMake(230, 280), controlPoint2: CGPointMake(245, 290)) //curve4
firePath.addCurveToPoint(CGPointMake(290, 220), controlPoint1: CGPointMake(250, 260), controlPoint2: CGPointMake(280, 270)) //curve5
firePath.addLineToPoint(CGPointMake(380, 200))
firePath.addLineToPoint(CGPointMake(380, 0))
firePath.addLineToPoint(CGPointMake(0, 0))
let fireNode = SKShapeNode(path: firePath.CGPath, centered: false)
fireNode.alpha = 0.2
fireNode.zPosition = Layer.Z4st+1
fireNode.lineWidth = 2
fireNode.strokeColor = SKColor.whiteColor()
fireNode.fillColor = SKColor.blueColor()
fireNode.position = CGPointMake(size.width/2, 0)
fireNode.name = "fireNode"
self.addChild(fireNode)
创建火开/关功能:
func fireTurnsOnOff () {
let playguitar: SKAudioNode
playguitar = SKAudioNode(fileNamed: "guitar.wav")
if firesoundon == false {
addChild(playguitar)
firesoundon = true
print("firesoundon is == \(firesoundon)")
}
else if firesoundon == true {
let stopguitar = SKAction.stop()
playguitar.runAction(stopguitar)
print("GuiterStopped")
firesoundon = false
print("firesoundon is == \(firesoundon)")
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let touchLocation = touch.locationInNode(self)
let node: SKNode = nodeAtPoint(touchLocation)
if node.name == "fireNode" {
fireTurnsOnOff()
}
}
}