It's a bug in the tutorial. The tutorial considers that gravity must not be applied when the Y velocity of the player is zero, but that can also happen at the top of the jump, therefore that condition is wrong. The concept is that gravity should not be applied when the player is in contact with the platform unless the player just jumped, but that should not be determined solely by checking if the Y velocity is zero.
Normal dt values are inexact and the Y velocity is very unlikely to hit zero, but by replacing dt with a more "exact" value, you're making it much more likely that it becomes exactly zero at the top of the jump. If you try for example 0.010101 you will see the character fall again.
Changing the condition to this works:
Code: Select all
if player.y < player.ground or player.y_velocity ~= 0 then
Edit: A similar bug applies to the condition for allowing the player to jump. As written, it's possible (but unlikely) that when the player is at the top of the jump, you can jump again. I've fixed it below as well.
Also, Pastebin is good for chat rooms, but in this forum at least, [ code ] tags or attachments are preferable.
Here's the fixed version:
Code: Select all
platform = {}
player = {}
function love.load()
platform.width = love.graphics.getWidth()
platform.height = love.graphics.getHeight()
platform.x = 0
platform.y = platform.height / 2
player.x = love.graphics.getWidth() / 2
player.y = love.graphics.getHeight() / 2
player.speed = 200
player.img = love.graphics.newImage('purple.png')
player.ground = player.y
player.y_velocity = 0
player.jump_height = -300
player.gravity = -500
end
function love.update(dt)
if love.keyboard.isDown('d') then
if player.x < (love.graphics.getWidth() - player.img:getWidth()) then
player.x = player.x + (player.speed * dt)
end
elseif love.keyboard.isDown('a') then
if player.x > 0 then
player.x = player.x - (player.speed * dt)
end
end
if love.keyboard.isDown('space') then
if player.y == player.ground then
player.y_velocity = player.jump_height
end
end
if player.y < player.ground or player.y_velocity ~= 0 then
player.y = player.y + player.y_velocity * dt
player.y_velocity = player.y_velocity - player.gravity * 0.01
end
i=dt
if player.y > player.ground then
player.y_velocity = 0
player.y = player.ground
end
end
function love.draw()
love.graphics.setColor(255, 255, 255)
love.graphics.rectangle('fill', platform.x, platform.y, platform.width, platform.height)
love.graphics.draw(player.img, player.x, player.y, 0, 1, 1, 0, 32)
love.graphics.print(i, 100, 100, 0, 10, 10)
end