Search code examples
swiftsprite-kittvosuiswipegesturerecognizer

Swipe gesture action is not called


I am trying to do basic 2D snake game for tv.

I have problem with gestures. I add gestures to view in didMoveToView(view: SKView) method inside GameScene class. This class also extends SKScene class. This is my didMoveToView method and handleSwipe method.

override func didMoveToView(view: SKView) {
    let swipeUp = UISwipeGestureRecognizer(target: self, action: "handleSwipe:")
    swipeUp.direction = .Up
    view.addGestureRecognizer(swipeUp)

    let swipeDown = UISwipeGestureRecognizer(target: self, action: "handleSwipe:")
    swipeDown.direction = .Down
    view.addGestureRecognizer(swipeDown)

    let swipeLeft = UISwipeGestureRecognizer(target: self, action: "handleSwipe:")
    swipeLeft.direction = .Left
    view.addGestureRecognizer(swipeLeft)

    let swipeRight = UISwipeGestureRecognizer(target: self, action: "handleSwipe:")
    swipeRight.direction = .Right
    view.addGestureRecognizer(swipeRight)

    backgroundColor = SKColor.blackColor()
}

func handleSwipe(sender: UIGestureRecognizer) {
    if let gesture = sender as? UISwipeGestureRecognizer {
        switch(gesture.direction) {
            case UISwipeGestureRecognizerDirection.Right: m_snake.moveRight()
            case UISwipeGestureRecognizerDirection.Left: m_snake.moveLeft()
            case UISwipeGestureRecognizerDirection.Up: m_snake.moveUp()
            case UISwipeGestureRecognizerDirection.Down: m_snake.moveDown()
            default:
                break
        }
    }
}

It seems like my program does not enter handleSwipe method when I swipe on remote. I am testing this on simulator. Any idea why this doesn't work?


Solution

  • func handleSwipes(sender:UISwipeGestureRecognizer) {
        if let gesture = sender as? UISwipeGestureRecognizer {
            switch(gesture.direction) {
                case UISwipeGestureRecognizerDirection.Right: m_snake.moveRight()
                case UISwipeGestureRecognizerDirection.Left: m_snake.moveLeft()
                case UISwipeGestureRecognizerDirection.Up: m_snake.moveUp()
                case UISwipeGestureRecognizerDirection.Down: m_snake.moveDown()
                default:
                    break
            }
        }
    }
    

    I just tested your code in my current project and it worked perfectly fine

    To get the swipe working, configure the simulator like this;

    • Show the remote by going to Hardware > Show Apple TV Remote
    • Hold down option while your mouse is over the trackpad.
    • Move the mouse sideways in a swipe movement