我有一个类,我想在其中封装所有与触摸有关的逻辑。但是,我还想将触摸事件传递给 GameScene
,以便我可以移除其他节点,例如。我认为 super.touchesBegan(touches, withEvent: event)
会工作,但没有骰子。
我也尝试过 Delegate
模式,但我也无法让它工作,而且我真的不喜欢这种方法。
import Foundation
import SpriteKit
class LevelSelect: SKSpriteNode {
var level:Int = 0
init(x: CGFloat, y: CGFloat) {
// init code ...
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// logic affecting this class
super.touchesBegan(touches, withEvent: event)
}
}
最佳答案
SKSpriteNode 的父类(super class)(super.touches...)不是 SKScene。
此外,当您将 touches 方法添加到 SKSpriteNode 子类时,它们只会在触摸实际节点而不是场景时触发。它通常用于诸如按钮子类之类的东西。
如果那是您想要的,您可以尝试将触摸直接转发到场景。每个 SKSpriteNode 都有一个可选的场景属性(在将 Sprite 添加到场景之前为 nil),使您可以访问节点所在的场景。
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// logic affecting this class
scene?.touchesBegan(touches, withEvent: event)
}
您还必须在 SKSpriteNode 类中激活用户交互,否则 touches 方法将不会触发。
isUserInteractionEnabled = true
一种更简单的方法是在您的 LevelSelect 类中为您需要完成的所有事情创建方法,例如
class LevelSelect: SKSpriteNode {
var level = 0
init(x: CGFloat, y: CGFloat) {
// init code ...
}
// Started touches
func didStartTouches() {
// do something
}
}
并且在您的 GameScene 中,您可以使用您创建的属性来初始化该类并调用方法。
class GameScene: SKScene {
levelSelect = LevelSelect(x: ..., y: ...)
...
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// logic affecting this class
levelSelect.didStartTouches()
}
}
要直接从您的 SKSpriteNode 类调用场景方法,您可以使用“as”运算符将通用场景属性转换为您的 GameScene,这样您就可以调用 GameScene 中的方法,例如
class LevelSelect: SKSpriteNode {
...
func callSomeMethodInGameScene() {
let gameScene = scene as? GameScene // dont use as!, always use optionals (as?) when doing the as casting
gameScene?.removeAllLabels()
}
}
希望对你有帮助
关于ios - Swift SKSpriteNode 类未将触摸注册到 GameScene,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42499637/