在Spritekit中区分Swipe和Touch - Swift 3

时间:2016-09-25 12:41:13

标签: ios swift sprite-kit touch gesture

我目前正在开发一个街机应用程序,用户点击该精灵跳过障碍物并向下滑动以使其在障碍物下滑动。我的问题是,当我开始滑动时,会调用touchesBegan函数,因此精灵跳跃而不是滑动。有没有办法区分这两个?

2 个答案:

答案 0 :(得分:2)

您可以使用手势状态来微调用户交互。手势是协调的,所以不应互相干扰。

func handlePanFrom(recognizer: UIPanGestureRecognizer) {
    if recognizer.state != .changed {
        return
    }

    // Handle pan here
}

func handleTapFrom(recognizer: UITapGestureRecognizer) {
    if recognizer.state != .ended {
        return
    }

    // Handle tap here
}

答案 1 :(得分:1)

如何轻微延迟触控?我有一个游戏,我使用延迟的SKAction做类似的事情。 (可选)你可以设置一个位置属性,让你的自己有一些摆动的空间,使用touchesMoved方法,因为某人有一个颤抖的手指(感谢KnightOfDragon)

let jumpDelayKey = "JumpDelayKey"
var startingTouchLocation: CGPoint?

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in: self)

        // starting touch location
        startingTouchLocation = location

        // start jump delay
        let action1 = SKAction.wait(forDuration: 0.05)
        let action2 = SKAction.run(jump)
        let sequence = SKAction.sequence([action1, action2])
        run(sequence, withKey: jumpDelayKey)
    }
}

func jump() {
   // your jumping code
}

请确保延迟时间不会太长,以免您的控件感到反应迟钝。四处寻找您想要的结果的价值。

如果已达到移动阈值,则在触摸移动方法中移除SKAction

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in: self)

        guard let startingTouchLocation = startingTouchLocation else { return }

        // adjust this value of how much you want to move before continuing
        let adjuster: CGFloat = 30

        guard location.y < (startingTouchLocation.y - adjuster) ||
              location.y > (startingTouchLocation.y + adjuster) ||
              location.x < (startingTouchLocation.x - adjuster) ||
              location.x > (startingTouchLocation.x + adjuster) else {     

return}

        // Remove jump action
        removeAction(forKey: jumpDelayKey)

        // your sliding code
    }
}

您可以使用手势识别器,但我不确定它是否会起作用以及它如何影响响​​应者链。

希望这有帮助