无法检测Sprite中是否在spritekit(SWIFT)中向左或向右移动spritenode

时间:2015-09-01 14:18:07

标签: swift sprite-kit

目前我正在使用swift spritekit进行游戏,并希望当手指在touchesMoved中向左移动角色时,角色会向左看。从那以后,我几天前开始用swift和spritekit进行开发,我觉得很难实现这个动作。如何在下面的代码中检测左或右?

   override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
        for touch in (touches as! Set<UITouch>) {
            let location = touch.locationInNode(self)

            playerSprite.position.x = touch.locationInNode(self).x

        }

2 个答案:

答案 0 :(得分:2)

您可以检查触摸的当前x位置是否大于或小于之前的位置。

要实现这一点,您应该创建一个变量来存储上次触摸的位置。例如:

var lastXTouch:CGFloat = -1

然后在touchesMoved方法中检查位置并检查前一个位置是左侧更多还是右侧更多:

override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
    for touch in (touches as! Set<UITouch>) {
        let location = touch.locationInNode(self)
        if lastXTouch > location.x{
            //Finger was moved to the left. Turn sprite to the left.
        }else{
            //Finger was moved to the right. Turn sprite to the right.
        }
        lastXTouch = location.x
        playerSprite.position.x = touch.locationInNode(self).x

    }

答案 1 :(得分:1)

当您希望能够检测到滑动时放入手势识别器:

var leftSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipe:"))
leftSwipe.direction = .Left

var rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipe:"))
rightSwipe.direction = .Right

self.view.addGestureRecognizer(leftSwipe)
self.view.addGestureRecognizer(rightSwipe)

然后,您需要实现名为 - handleSwipe:

的处理程序方法
func handleSwipe(sender:UISwipeGestureRecognizer){
   if (sender.direction == .Left){
       //swiped left
       //change your texture here on the sprite node to make it look left
   }
   if (sender.direction == .Right){
       //swipe right
       //change texture here on sprite to make it look right
   }
}