cancelling a tap gesture recongiser

2019-09-02 02:06发布

问题:

Referring to my last question:

Sprite moves two places after being paused and then unpaused

Hi, I have a tap gesture which moves a sprite in my game forward 1 space and when I press the pause button it continues to register the tap gesture and then when I resume the gameplay It moves two spaces.

so I managed to define a bool variable that detects (using if statements) if I have paused the tap gesture

var tapIsPaused: Bool = false



func tapUp(){

    if(tapIsPaused == true) {

        //do nothing


    } else if (tapIsPaused == false) {

        let amountToMove:CGFloat = levelUnitHeight

        let move:SKAction = SKAction.moveByX(0, y: amountToMove, duration: 0.1)


        menubutton.hidden = true
        settingsButton.hidden = true
        highscoreLabel.hidden = true
        pauseButton.hidden = false

        thePlayer.runAction(move)

        clearNodes()

    }

}

But the problem I have now is that when I press the resume button to resume the gameplay it still moves the sprite, but this time it's only moving one space up, which is because when I press the resume button it turns the tap on which then registers the tap of the resume button to move the player up.

How can I fix this?

Here is my pause button:

 else if (node == pauseButton) {

        tapIsPaused = true
        pauseButton.removeFromParent()
        addChild(resumeButton)
        addChild(restartButton)
        self.runAction (SKAction.runBlock(self.pauseGame))

    }

Here is my resume button:

 else if (node == resumeButton) {


        resumeButton.removeFromParent()
        restartButton.removeFromParent()
        addChild(pauseButton)
        self.runAction (SKAction.runBlock(self.resumeGame))
        tapIsPaused = false

    }

Here is my tap gesture handler code:

 let TapUpRec = UITapGestureRecognizer()




 TapUpRec.addTarget(self, action: "tapUp")
    self.view!.addGestureRecognizer(TapUpRec)

回答1:

You can remove Gesture on Pause click using following:

self.view.removeGestureRecognizer(YOUR_GESTURE_RECOGNISER)

and add it again if resume game



回答2:

Modify your resume function as:

 else if (node == resumeButton) {

    resumeButton.removeFromParent()
    restartButton.removeFromParent()
    addChild(pauseButton)
    tapIsPaused = false
    self.runAction (SKAction.runBlock(self.resumeGame))
}


回答3:

Very simple and easiest way.No need to add or remove Gesture.

You can do it with enable or disable your gesture.

For swift 2.3

TapUpRec.enabled = false //pause click

TapUpRec.enabled = true //resume click

For swift 3.0

TapUpRec.isEnabled = false //pause click

TapUpRec.isEnabled = true //resume click