Search code examples
swiftsprite-kitmoveswipe-gesture

Using Swipe Recognizer in SpriteKit


I'm trying to implement swipe gestures left and right into a game in SpriteKit where the player collects falling objects spawning from the top of the screen. The problem I'm facing is trying to keep a continuous movement of the player while the finger is on the screen until the touch is ended and the player stays where the last touch ended. There might be a better way to implement this other than swipe gestures hence why I'm asking you guys! Any help would be great, thank you all!


Solution

  • This is not something you want to use a swipe (I think you are using pan) gesture for. What you want to do is override the touchesBegan, touchesMoved, and touchesEnded calls on the scene, and plan your movement according to these 3 methods.

    You are probably going to want to use SKAction.move(to:duration:) with these methods, and figure out the math to keep a constant speed.

    E.G.

    func movePlayer(to position:CGPoint)
    {
      let distance = player.position.distance(to:position)
      let move = SKAction.move(to:position, duration: distance / 100) // I want my player to move 100 points per second
      //using a key will cancel the last move action
      player.runAction(move,withKey:"playerMoving")
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) 
    {
      let touch = touches.first
      let position = touch.location(in node:self)
      movePlayer(to:position)
    }
    
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) 
    {
      let touch = touches.first
      let position = touch.location(in node:self)
      movePlayer(to:position)
    }
    
    
    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
      let touch = touches.first
      let position = touch.location(in node:self)
      movePlayer(to:position)
    }