Swift - 从IBAction按钮调用SKAction(在课堂上)

时间:2017-03-22 12:56:50

标签: ios swift avaudioplayer ibaction skview

我是Swift的新手 - 经过这么多时间的搜索,我需要专业人士的帮助:D

使用Swift放置一个小型IOS应用程序,这是结构:

  • GameViewcontroller
  • GameScene

在GameScene中,我放了一个小图片:

class GameScene: SKScene {
private var tanzschuhR: SKSpriteNode!
override func didMove(to view: SKView) {

    self.size = CGSize(width: 1024, height: 1024)
    self.backgroundColor = .gray
    self.scaleMode = .aspectFill

    let startPt = CGPoint(x: 500, y: 400)
    tanzschuhR = SKSpriteNode(imageNamed: `SchuhR`)
    tanzschuhR.position = startPt
    tanzschuhR.zPosition = 1

    self.addChild(tanzschuhR)

    func swingPattern1() {
        // move it
        let negDelta = CGVector(dx: -50, dy: -50)
        let action = SKAction.move(by: negDelta, duration: 4)
        tanzschuhR.run(action)
    }
}
}

现在,我只想从GameViewController中的IBAction按钮启动函数swingPattern1(),以便开始将图像同步移动到正在播放的音频。

这是按钮的一部分:

@IBAction func playIt(_ sender: UIButton) {
    playMultipleSound()
// no idea to call the function swingPattern1()
// always get an error
}

那么,有人可以帮助我吗?

如果点击按钮,如何调用此功能?

或者是否有其他更好的方法可以通过点按按钮来启动音频?

非常感谢你的帮助......

更新:

我将var放在IBAction中:

@IBAction func playIt(_ sender: UIButton) {
    playMultipleSound()
    let gameScene = GameScene()
    gameScene.swingPattern1()

}

不知道,如果它是正确的语法 - 抱歉......:D

在BUILD& RUN之后,我收到此错误:

enter image description here

该应用停止...

1 个答案:

答案 0 :(得分:0)

首先,将swingPattern1移到didMove(to view: SKView)

之外
class GameScene: SKScene {
    private var tanzschuhR: SKSpriteNode!
    override func didMove(to view: SKView) {

        self.size = CGSize(width: 1024, height: 1024)
        self.backgroundColor = .gray
        self.scaleMode = .aspectFill

        let startPt = CGPoint(x: 500, y: 400)
        tanzschuhR = SKSpriteNode(imageNamed: `SchuhR`)
        tanzschuhR.position = startPt
        tanzschuhR.zPosition = 1

        self.addChild(tanzschuhR)
    }

    func swingPattern1() {
        // move it
        let negDelta = CGVector(dx: -50, dy: -50)
        let action = SKAction.move(by: negDelta, duration: 4)
        tanzschuhR.run(action)
    }
}

然后在你的视图控制器中......

@IBAction func playIt(_ sender: UIButton) {
    playMultipleSound()

    // Assuming you already have a var gameScene: GameScene
    gameScene.swingPattern1()
}