我正在寻求帮助以解决我已经困扰了一段时间但找不到答案的问题。
我有一个 SpriteKit child 游戏应用程序,用户可以在其中在屏幕上拖动对象 (SKspriteNodes)。这是在“触摸”事件中控制的,如下所示:
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
super.touchesBegan(touches, withEvent: event)
let touch = touches.first as! UITouch
let touchLocation = touch.locationInNode(self)
if piece01.containsPoint(touchLocation) && piece01Placed == false && aPieceIsBeingGrabbed == false {
piece01Grabbed = true
aPieceIsBeingGrabbed = true
self.piece01.zPosition = 4.0
}
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
super.touchesMoved(touches, withEvent: event)
let touch = touches.first as! UITouch
let touchLocation = touch.locationInNode(self)
if piece01Grabbed && piece01Placed == false {
self.piece01.position = CGPointMake(touchLocation.x + worldScale * 120, touchLocation.y - worldScale * 80)
}
}
我的问题是,如果用户在拖动 sprite 时触摸屏幕的另一部分,则会出现故障,Sprite 在两个触摸位置之间来回弹跳,无法决定留在哪个位置。
有谁知道我怎样才能防止这种情况发生,以便 Sprite 始终遵循它最初被捕获的触摸?提前致谢!
最佳答案
根据我的问题,MaceDevs 的上述答案是正确的,并且可以像我最初询问的那样与 TouchMoved 事件一起使用。但是,我发现使用手势识别器来处理拖动事件更容易。
为了解决这个问题,我最终放弃了“触摸”方法并实现了 UIPanGestureRecognizer。
您所要做的就是在 didMoveToView 中设置一个 UIPanGestureRecognizer 并将其最大触摸次数设置为 1。如果您不将其设置为 1,则任何其他触摸都会沿触摸的平均方向移动该 block 。
//Declare "draggingPiece" variable at top of swift file
var draggingPiece: UIPanGestureRecognizer!
//...init functions...
override func didMoveToView(view: SKView) {
//Enable the gesture recognizer
draggingPiece = UIPanGestureRecognizer(target: self, action: Selector("dragPiece:"))
draggingPiece.maximumNumberOfTouches = 1
self.view?.addGestureRecognizer(draggingPiece)
}
func dragPiece(recognizer: UIPanGestureRecognizer) {
if recognizer.state == UIGestureRecognizerState.Began {
}else if recognizer.state == UIGestureRecognizerState.Changed {
}else if recognizer.state == UIGestureRecognizerState.Ended {
}
}
然后删除willMoveFromView中的手势识别器:
self.view?.removeGestureRecognizer(draggingPiece)
关于ios - 如何防止额外的触摸干扰拖动位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30426993/