【问题标题】:Unable to detect if the spritenode is moved to the left or right in spritekit (SWIFT)无法检测 spritenode 在 spritekit (SWIFT) 中是向左还是向右移动
【发布时间】:2015-09-01 14:18:07
【问题描述】:

目前我正在使用 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

        }

【问题讨论】:

  • 使用可以检测左右滑动的手势识别器。对你来说会比使用touches: 容易得多
  • 是不是应该把toucheMoved换成某个手势识别器?
  • 如果您使用 touchesMoved 来拖动精灵,则保留它,但要检测左右运动,则更容易放入手势识别器,以便更改精灵的纹理跨度>
  • 谢谢!我会试试的!
  • 祝你好运,我在下面给了你一个模板来开始:)

标签: swift sprite-kit


【解决方案1】:

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

为此,您应该创建一个变量来存储您最后一次触摸的位置。例如:

var lastXTouch:CGFloat = -1

然后在 touchesMoved-method 中检查位置并检查之前的位置是更多在左侧还是更多在右侧:

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

    }

【讨论】:

  • 感谢克里斯蒂安!你的代码就像一个魅力!没想到这么简单!
  • 如果您使用其他答案(您已接受的答案),请记住它仅适用于滑动。它不会真正对您的触摸动作做出反应。滑动不是您真正想要的(afaik)。
  • @Christian 如果您在滑动/平移的任何方向上拖动手指......所以手势识别器将在这里工作。您确实意识到,从定义上讲,滑动或平移就是触摸运动??
  • @MaxKargin 是的,我愿意。但是 swiperecognizer 并不真正适合他的需求。查看 Apple 文档:developer.apple.com/library/ios/documentation/UIKit/Reference/… 滑动必须在一个方向上精确。还必须设置 numberOfTouches 等。
  • @Christian 你以前用过滑动或平底锅吗?识别器正在做你在这里所做的事情,除了它内置了错误处理并且更安全。如果您有杂散的触摸,您的方法将不起作用。
【解决方案2】:

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

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
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多