Search code examples
swiftsprite-kitskphysicsbody

SpriteKit Swift: How to make a sprite jump in place when tapped?


So Ive been working on a game and have a little sprite that is currently running in place. I need to make him jump up whenever the user taps the screen to dodge obstacles. I also need him to return to his starting point on the ground after he jumps.


Solution

  • Using physics is overkill for a game like this. Not even the 2D Mario games use physics so I doubt you will need it.

    As a very simple implementation you can use a sequence of SKActions.

    // move up 20
    let jumpUpAction = SKAction.moveBy(x: 0, y: 20, duration: 0.2)
    // move down 20
    let jumpDownAction = SKAction.moveBy(x: 0, y: -20, duration: 0.2)
    // sequence of move yup then down
    let jumpSequence = SKAction.sequence([jumpUpAction, jumpDownAction])
    
    // make player run sequence
    player.run(jumpSequence)
    

    That should work. I may have mistyped something in the browser though.

    You can tweak this to make the jump look more natural. Maybe add a few more steps to the jump process to change the speed of the rise/fall over time to make it look like he's accelerating. etc...