ios - 如何防止额外的触摸干扰拖动位置

标签 ios swift sprite-kit skspritenode

我正在寻求帮助以解决我已经困扰了一段时间但找不到答案的问题。

我有一个 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/

相关文章:

ios - 自定义类函数不适用于场景

ios - 错误 :Storyboard doesn't contain a view controller with identifier 'jailBrokenViewController' '

ios - 当 ForEach 中发生 onDelete 时如何更新其他 CoreData?

facebook - swift:Xcode 无法为 Facebook 框架生成 Swift 表示

ios - RxSwift - 将序列拆分成更小的序列以连接

ios - SKAction 跟随路径同时进行定向和旋转

iphone - 是否可以更改本地化的默认英语语言?

ios - iOS 中的断断续续的动画

协议(protocol)中使用的 Swift 通用类型不起作用

ios - 在 SpriteKit 项目中使用 Sprite 图集、纹理图集或 Assets 目录