Search code examples
iosswifttouchesbegan

I have a touches began method but I don't want the sprite to jump again if touched twice?


I have this touches began method which causes the sprite to jump. If I continue to tap the sprite it goes up continuously. I want to stop this but I also need to be able and hop over another object about 0.8 seconds later.

  override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    /* Called when a touch begins */
    if moving.speed > 0  {
        for touch: AnyObject in touches {
            let location = touch.locationInNode(self)

            hurdie.physicsBody?.velocity = CGVectorMake(0, 0)
            hurdie.physicsBody?.applyImpulse(CGVectorMake(0, 30.0))


        }

Solution

  • I suggest you use a bool to know whether the player should jump or not, and use an NSTimer to set this bool, like this:

    var shouldJump = true;
    
    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        /* Called when a touch begins */
        if moving.speed > 0  {
            for touch: AnyObject in touches {
                let location = touch.locationInNode(self)
                if (shouldJump){
                    hurdie.physicsBody?.velocity = CGVectorMake(0, 0)
                    hurdie.physicsBody?.applyImpulse(CGVectorMake(0, 30.0))
                    shouldJump = false;
                    var timer = NSTimer.scheduledTimerWithTimeInterval(0.8, target: self, selector: Selector("updateState"), userInfo: nil, repeats: false)
                }
    
            }
    func updateState() {
         shouldJump = true;
         }