The fundamentals of jumping in a 2D game are all quite simple when broken down into their core routines. While getting a good handle on physics and trig would be a good idea in general, I feel it's extreme overkill for a simple implementation.
Here's my take on it, at least:
In the most straightforward explanation, begin with a few variables to keep track of what the character is currently doing and where he is.
Also we should come up with some "physics" constants that generally make sense. All we're worried about here is upward acceleration and gravity.
This might look like:
Code: Select all
hero = {} -- Set up a table for our character. Just to keep things neat.
hero.x = 400
hero.y = 500
hero.vel = 0 -- Start with no velocity.
hero.can_jump = true -- This will be our boolean that we flip when he's on the ground
hero.jump_acc = -8 -- These values tend to
hero.gravity = .5 -- work for a basic test.
floor_y = 500 -- This is our bottom of the map.
In our example, we always add the hero.vel to hero.y
Normally hero.vel = 0 so this does nothing. But when hero.vel changes, the position of our hero starts to change:
Code: Select all
hero.y = hero.y + hero.vel
if not hero.can_jump then -- if hero.can_jump is false, then we must be jumping, so we begin to add gravity.
hero.vel = hero.vel + hero.gravity
end
if hero.y > floor_y then -- if we've hit the floor...
hero.vel = 0 -- Remove the velocity from the character.
hero.y = floor_y -- Make sure he's sitting squarely on the ground.
hero.can_jump = true -- And now he's allowed to jump again
end
Code: Select all
if hero.can_jump then -- Only allow him to jump if hero.can_jump == true
hero.vel = hero.jump_acc -- This makes hero.vel = -8
hero.can_jump = false -- Tell our hero he can't jump another time
end
Code: Select all
function love.draw()
love.graphics.rectangle("fill", hero.x, hero.y, 32,32)
end
This is the bare bones basics of the jumping concept. After this point, you still have your work cut out for you.
I would look into these topics next as further reading:
2D collision detection:
AABB to AABB (Axis Aligned Bounding Box)
AABB to Circle
Circle to Circle (extremely easy)
2D Quadtrees (helpful for checking lots of collisions)
Edited for code corrections