Update: Thanks to great comments the double jump for this post has been fixed.
If you’ve been following my other Corona SDK tutorial posts on www.thatssopanda.com (see the previous one here – http://thatssopanda.com/corona-sdk-tutorials/making-a-character-jump-in-corona-sdk/), you can see our little game start to take shape. So far, we’ve covered how to move our guy and make our guy jump using the Corona SDK platform. In today’s post, I want to slow down a bit and refine our guy’s movement. We have two objectives.
1) Don’t let our guy go off screen
2) Only allow one jump
Part 1) There are several ways to accomplish keeping your character on-screen and I feel the easiest way, especially for beginners, is to add two walls to the outside of the screen. We will add one wall 5 pixels to the left of the screen, or x = -5. And we will add a right wall 5 pixels to the right of the screen, or x = Screen Width + 5. Here’s the code.
-- Add Left Wall local left_wall = display.newRect(-5,0,5,_H) physics.addBody( left_wall, "static" ) -- Add Right Wall local right_wall = display.newRect(_W+5,0,5,_H) physics.addBody( right_wall, "static")
There are a ton of ways to implement keeping a character on screen, but this is one of the easiest ways.
Part 2) To allow only a single jump, we have to add a Runtime Collision Listener. This listener will let us know when our guy is in the air and when he’s touching the ground. It’s not perfect, but in our case, it will work. Here’s the code.
-- Make character jump function up:touch(event) if(event.phase == "began" and playerInAir == false) then playerInAir = true guy:setLinearVelocity( 0, -200 ) print(playerInAir) end end up:addEventListener("touch",up) -- Detect whether the player is in the air or not function onCollision( event ) if(event.phase == "began") then if(event.object1.myName == "grass" and event.object2.myName == "guy") then playerInAir = false; end end end Runtime:addEventListener( "collision", onCollision )
And that’s it for today’s post! If you would like to see more tutorials, please leave a comment. This helps keep me motivated to continue to bring high quality tutorials to your site. As always, you can download the full source below. As always, you can download the full source below.