Diagonal swipe gestures

Working from the trigonometry example I wanted to repurpose the laser logic to the ship’s movement, to control the ship with swipes in all directions, in place of the default N/S/E/W UISwipeGestureRecognizer.

Using the trigonometry example I would be able to add custom easing/tweening at the beginning and end of the movement. The idea being to swipe anywhere on screen to control a node.

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

  let touchTimeThreshold: CFTimeInterval = 0.3
        let touchDistanceThreshold: CGFloat = 1     // if the swipe distance is less then it is registered as a tap event
        var destination = CGPoint.zero
        var moveDistance: CGFloat = 20

        guard CACurrentMediaTime() - touchTime < touchTimeThreshold,
              let touch = touches.first else { return }

        let location = touch.location(in: self)

        let swipe = CGVector(dx: location.x - touchLocation.x, dy: location.y - touchLocation.y)
        let swipeLength = sqrt(swipe.dx * swipe.dx + swipe.dy * swipe.dy)

        guard swipeLength > touchDistanceThreshold else { return }
        let angle = atan2(swipe.dy, swipe.dx)   // convert the swipe vector to an angle

        //access the sprite node on the Entity
        guard let spriteComponent = hero.component(ofType: SpriteComponent.self) else { return }

                    if swipe.dy > 0 {

                destination.y = moveDistance
            } else {
                destination.y = -moveDistance
            }
                destination.x = spriteComponent.node.position.x +
                  ((destination.y - spriteComponent.node.position.y) / swipe.dy * swipe.dx)

           if swipe.dx > 0 {
                destination.x = moveDistance
            } else {
                destination.x = -moveDistance
            }
                destination.y = spriteComponent.node.position.y +
                  ((destination.x - spriteComponent.node.position.x) / swipe.dx * swipe.dy)

        spriteComponent.moveAnimation(theXAmount: destination.x, theYAmount: destination.y, theAnimation: "walkLeft")
}

However, it doesn’t work much beyond five swipes, as they add up the previous numbers on either x/y axis, and often the ship will get stuck on the side of the screen.

Basically I am looking for diagonal swipe gestures and thought that trig would be the way to achieve that.

Is it possible to subclass Apple’s UISwipeGestureRecognizer to add diagonal functionality ?

I also found that the UITapGestureRecognizer in touchesEnded would conflict with touchesMoved. The trigonometry example could solve this.

ref : Trigonometry for Game Programming – SpriteKit and Swift Tutorial: Part 2/2 | raywenderlich.com

This topic was automatically closed after 166 days. New replies are no longer allowed.