How to make a character jump with Linear Force

In this post, you’ll learn how to make a character jump using linear velocity with Corona SDK. To make the character jump, you’ll learn how to require physics, start physics, and physic bodies to the game objects.

display.setStatusBar(display.HiddenStatusBar)
local physics = require "physics"
physics.start()
 
local ground = display.newImage("ground.png")
  ground.x = 160
  ground.y = 460
  physics.addBody(ground, "static")
 
local player = display.newImage("player.png")
  player.x = 160
  player.y = 300
  physics.addBody(player)

Up to this point, we’ve hidden the status bar, required in physics, and added a ground object and a player object. In the next part, we’ll create the function onTouch() and add an event listener that will call the onTouch() funciton.

Inside of the onTouch() function is where the player will jump. We’ll set the players linear velocity to according to the touch event. If the player touches to the left of the on-screen player, then the on-screen player will jump left. And the same is true for jumping right.

setLinearVelocity() is used by setting the x and y values. In both cases, the y value is a negative number to force the player up. The x value is postive or negative depending on the location of the touch.

local function onTouch(event)
    if(event.phase == "began") then 
        if(event.x < player.x) then 
            -- jump left
            player:setLinearVelocity(-30, -200)
        else 
            -- jump right
            player:setLinearVelocity(30, -200)
        end
    end
end
Runtime:addEventListener("touch", onTouch)

And that’s it to using linear velocity to making a player jump!

Download the full source code.

Daniel Williams

Leave a Reply

Your email address will not be published. Required fields are marked *