我是 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 之后,我得到这个错误:
应用程序停止...
最佳答案
首先,将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/