我在SKScene中有一个节点,我将根据用户的触摸来移动它。基本上,这个字符也应该试图跟随用户的手指(假设手指在屏幕上)。我目前已经按原样实现了它,它工作得很好:
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
let touch = touches.first as! UITouch
player.runAction(SKAction.moveTo(touch.locationInNode(self), duration: 1))
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
let touch = touches.first as! UITouch
player.runAction(SKAction.moveTo(touch.locationInNode(self), duration: 1))
}
override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
player.removeAllActions()
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
player.removeAllActions()
}然而,问题是如果用户在电话上握住他/她的手指。touchesBegan只被调用一次,而这是在启动时,而不是当它被保持。我想让玩家的角色不断的尝试着触及手指。
我在节点上对着摄像头,所以节点唯一接触手指的时间应该是用户将手指放在节点上/在节点中(即,与节点相同的位置)。因此,在运行SKAction以移动节点后,触摸是无效的,因为它位于旧位置。
我该怎么做?
发布于 2015-05-22 08:48:04
将两个实例变量添加到SKScene、BOOL fingerIsTouching和CGPoint touchLocation中。
在-touchesBegan:内部,将fingerIsTouching设置为YES,并将touchLocation更新到正确的位置。在SKScene的-update:方法中,检查fingerIsTouching是否为YES,并根据touchLocation移动字符。我建议使用-update:,因为它每帧调用一次,这就足够了。不过,您可能需要使用一些其他方法来移动字符,而不是SKAction。
不要忘记在-touchesMoved:中更新fingerIsTouching,并在-touchesCancelled:和-touchesEnded:中重置fingerIsTouching :)
抱歉,奥比克,希望这说明了这一点。
发布于 2015-05-19 23:16:52
您可以注册这样的长触摸事件:
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "longPressed:")
self.view.addGestureRecognizer(longPressRecognizer)
func longPressed(sender: UILongPressGestureRecognizer) {
// your code
}发布于 2017-08-15 10:50:22
For Swift 4:
您首先要使GameScene成为UIGestureRecognizerDelegate
class GameScene: SKScene, UIGestureRecognizerDelegate {因此,还需要将委托方法添加到GameScene类中:
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}然后在GameScene的override func didMove(to view: SKView) {中添加以下内容:
let pressed:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPress(sender:)))
pressed.delegate = self
pressed.minimumPressDuration = 0.1
view.addGestureRecognizer(pressed)最后,在GameScene中添加您的函数来处理长新闻(您也可以在其中识别long press的状态):
func longPress(sender: UILongPressGestureRecognizer) {
if sender.state == .began { print("LongPress BEGAN detected") }
if sender.state == .ended { print("LongPress ENDED detected") }
}https://stackoverflow.com/questions/30337608
复制相似问题