ios - Swift - 从 IBAction 按钮调用 SKAction(在类里面)

标签 ios swift avaudioplayer ibaction skview

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

用Swift规划一个小的IOS App,结构是这样的:

  • 游戏 View Controller
  • 游戏场景

在 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

应用程序停止...

最佳答案

首先,将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)
    }
}

然后在你的 View Controller 中......

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

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

关于ios - Swift - 从 IBAction 按钮调用 SKAction(在类里面),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42952295/

相关文章:

ios - 如何使用 Swift 打开谷歌地图以显示路线

audio - 使用MonoTouch进行多声道声音播放

ios - 获取本地音频文件的AVURLAsset

iphone - 在 NSUserDefaults 中保存 ALAsset URL

ios - 仅当隐藏文本字段时才使用键盘移动 View

ios - 重新加载表格 View 而不影响单元格中的倒数计时器

ios - 锁定时 AVAudioPlayer 在 iPhone 5 中不播放音频

ios - Sqlite 查询也可以获取带有相邻词的搜索词

ios - didSelectItemAtIndexPath 未在同一屏幕上使用多个 Collection View 调用

swift - AWS Amplify pod 安装依赖项版本错误