Issue with getting Hero to jump

I am developing a side scroller game and running into an issue with getting the hero to reliably jump, I have a GameScene class that calls the jump function from the hero class every time the screen is tapped. Below is the code from the hero class that handles jumping.


The problem I'm having is that the hero doesn't always jump when it's supposed to. Anyone have any ideas on how better to implement the jump? I just want it to jump on every tap, if it's already jumpping than a 2nd tap should not cause a double jump.



note: My hero extends SKSpriteNode

    // rendered on each frame
    func update() {
        if isOnGround == true && jumpNow == true && isJumping == false {
            isOnGround = false
            groundY = position.y - 1
            isJumping = true
            jumpNow  = false
            runAnimation()
        }
       
        if isJumping == true {
            runJumpAnimation()
            self.physicsBody!.applyImpulse(CGVector(dx: 0.0, dy: 300))
            isJumping = false
        }
        /
        if isJumping == false && isOnGround == false && (position.y == previousY) {
            isOnGround = true
        }
        previousY = position.y
    }
   
    // called from game scene on every touches began.
    func jump() {
        if (position.y == previousY) { // I suspect the problem is here, but this is the only way I can keep the hero from double jumping
            jumpNow = true
        }
    }

hey adiaz


try this:


In your gameScene:



var jumped = false

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    
        for touch: AnyObject in touches {

if jumped == false{
     jumped = true
     heroJump()
}
   
}
}


And then implement a physicsbody for the ground and for the hero. And every time the hero contacts the the ground you set the variable jumped to false again.


Hope this helps a bit.


For more information about physicsbody. Read on the web about SKPhysicsbody...

Thanks Hardwell,

That works a lot better, but it introduces a new issue.

If I tap fast enough, I can get the hero to double jump or jump higher than normal. Could it be that if the hero is on the ground long enough, the didBeginContact function is getting called nonstop and creates a buffer?

Accepted Answer

Add this to your heroJump function:


set the velocity always to zero before you apply an impulse..


physicsbody.velocity = cgVectorMake(0,0)

self.physicsBody!.applyImpulse(CGVector(dx: 0.0, dy: 300))


I solved the problem like this in one of my projects..


And also set the property of the ground to "not bumpy", i don't remember how the exact property is called..


I hope this works.

perfect, thanks for your help.

Issue with getting Hero to jump
 
 
Q