In your game scene, add a new jump()
method that is called from touchesBegan
. Use touchesBegan
and touchesEnded
to set a bool that tracks when you are touching the screen. You can use the didBegin
method of your scene to keep track of when the player lands on the ground (or collides with obstacles, etc).
Something like this:
class GameScene: SKScene, SKPhysicsContactDelegate {
var person = SKSpriteNode()
var isJumping = Bool()
var isTouching = Bool()
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
isTouching = true
jump()
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
isTouching = false
}
func jump(){
if isTouching == true {
if isJumping == false {
person.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 600))
isJumping = true
}
}
}
func didBegin(_ contact: SKPhysicsContact) {
let bodyA = contact.bodyA.node
let bodyB = contact.bodyB.node
// Collided with ground
if bodyA?.physicsBody?.categoryBitMask == 2 && bodyB?.physicsBody?.categoryBitMask == 1 {
isJumping = false
jump()
}
}
}