我目前正在使用Swift3和Spritekit编写2D无尽奔跑游戏。我最近添加了一些代码以便于检测swipes的操作(如下所示)。我的问题是:如何在Spritekit节点上检测滑动动作并检查其方向?我意识到这个问题之前已经被问过,但我找不到适用于Swift3的解决方案,因为我遇到的所有东西似乎都是Swift和Swift2的。
以下是我的滑动检测代码:
它还显示以下内容。
在与致命错误声明相同的行上。
以下是我的滑动检测代码:
override func viewDidLoad() {
super.viewDidLoad()
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
swipeLeft.direction = UISwipeGestureRecognizerDirection.left
self.view.addGestureRecognizer(swipeLeft)
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
swipeRight.direction = UISwipeGestureRecognizerDirection.right
self.view.addGestureRecognizer(swipeRight)
let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
swipeUp.direction = UISwipeGestureRecognizerDirection.up
self.view.addGestureRecognizer(swipeUp)
let swipeDown = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
swipeDown.direction = UISwipeGestureRecognizerDirection.down
self.view.addGestureRecognizer(swipeDown)
}
我已经使用一个函数进行了测试:
func respondToSwipeGesture(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.right:
print("Swiped right")
case UISwipeGestureRecognizerDirection.down:
print("Swiped down")
case UISwipeGestureRecognizerDirection.left:
print("Swiped left")
case UISwipeGestureRecognizerDirection.up:
print("Swiped up")
default:
break
}
}
}
手势似乎正常工作,因为打印语句已经正确地显示了我的手势反应结果。
我还添加了一个代理以避免可能的SIGABRT错误:
class GameViewController: UIViewController, UIGestureRecognizerDelegate
如果您需要更多的信息,请告诉我!
编辑: 添加了初始化拼图块的代码
//The class
class ChoosePiecesClass: SKSpriteNode{
func moveWithCamera() {
self.position.x += 5;
}
//initialize a piece
private var RandomPiece1: ChoosePiecesClass?;
override func didMove(to view: SKView) {
RandomPiece1 = childNode(withName: "RandomPiece1") as? ChoosePiecesClass;
RandomPiece1?.position.x = 195;
RandomPiece1?.position.y = -251;
}
override func update(_ currentTime: TimeInterval) {
RandomPiece1?.moveWithCamera();
}
编辑以提供控制台中的错误语句,单击“开始游戏”并触发致命错误代码,导致游戏崩溃。
fatal error: init(coder:) has not been implemented: file /Users/ardemis/Documents/PuzzleRunner/PuzzleRunner 3 V3/PuzzleRunner/ChoosePieces.swift, line 33
它还显示以下内容。
EXEC_BAT_INSTRUCTION(code = EXEC_1386_INVOP, subcode = 0x0)
在与致命错误声明相同的行上。