0
votes

I'm trying to make a ball, SKSpriteNode, move in ALL directions including diagonals and all other directions. UIGesture doesn't work with it so I need to use UIPanGesture but I have no idea how to implement it into a SpriteKit file. This is what I have so far. Any help?? The ball sprite node is called "ball".

func handlePan(recognizer:UIPanGestureRecognizer) {
  let translation = recognizer.translation(in: self.view)
  if let view = recognizer.view {
    view.center = CGPoint(x:view.center.x + translation.x,
                            y:view.center.y + translation.y)
  }
  recognizer.setTranslation(CGPoint.zero, in: self.view)
}
1

1 Answers

0
votes

Note that SpriteKit and UIKit have totally different coordinate systems (Spritekit is Cartesian, UIKit is reflected about the X axis) so you cannot use UIKit coordinates in Spritekit without conversion. Fortunately SKScene and SKNode have methods to convert points from a SKView and from other SKNodes into a nodes local space.

@objc private func pan(_ recognizer: UIPanGestureRecognizer) {
    let pointInView = recognizer.location(in: view)
    let pointInScene = convertPoint(fromView: pointInView)

    switch recognizer.state {
    case .began:
        //Start dragging on the ball, or ignore this gesture
        isPanning = atPoint(pointInScene) == ball
    case .changed:
        //Move the ball
        guard isPanning else {
            return
        }
        let translation = recognizer.translation(in: view)
        ball.position.x -= translation.x
        ball.position.y += translation.y
        recognizer.setTranslation(.zero, in: view)
    case .cancelled, .ended:
        //Stop dragging
        isPanning == false
    default:
        break
}

I have a full example on my GitHub here: https://github.com/joshuajhomann/AngryBirdsClone