You just need to think of it in physics terms. The gravity you want seems to be either a realistic decceleration upwards followed by acceleration towards the bottom of the screen, or if not, at least a non-instant trip to the peak of the jump.
To do that you need to give the bodies an actual speed variable and modify their position according to their speed each frame (like you've been doing with the "190" everywhere but for the jump). The jump itself should modify the y speed value rather than the position.
Code: Select all
require "external"
block = {}
player = {}
local collision = false
jump = true
moveleft = true
moveright = true
--load the images
background_img = love.graphics.newImage("textures/photo.png")
block_img = love.graphics.newImage("textures/block.png")
player_img = love.graphics.newImage("textures/player.png")
function love.load()
player.x = 0
player.y = 0
player.xspeed = 0
player.yspeed = 0
table.insert(block, {x = 0, y = 50})
table.insert(block, {x = 50, y = 50})
table.insert(block, {x = 150, y = 200})
for i=1,3 do
table.insert(block, {x = 150+i*50, y = 200})
end
end
function love.draw()
x, y = love.mouse.getPosition()
--draw the background
love.graphics.setColor(255, 130, 130, 255)
love.graphics.draw(background_img, 0, 0)
--draw the blocks
love.graphics.setColor(255, 255, 255, 255)
love.graphics.draw(block_img, x, y)
for i, v in pairs(block) do
love.graphics.draw(block_img, block[i].x, block[i].y)
end
--draw the player
love.graphics.setColor(255, 130, 130, 255)
love.graphics.draw(player_img, player.x, player.y)
end
function love.update(dt)
x, y = love.mouse.getPosition()
if love.mouse.isDown("l") then
table.insert(block, {x = x, y = y})
end
hitboxes:update(dt)
--move left
if moveleft == true then
if love.keyboard.isDown("left") then
player.xspeed = -190
else
player.xspeed = 0
end
end
--move right
if moveright == true then
if love.keyboard.isDown("right") then
player.xspeed =190
else
player.xspeed = 0
end
end
player.x = player.x + player.xspeed * dt
player.y = player.y + player.yspeed * dt
end
function love.keypressed(key)
--jump
if key == " " then
if jump == true then
jump = false
player.yspeed = player.yspeed - 380
else
jump = true
end
end
end
function CheckCollision(x1,y1,w1,h1, x2,y2,w2,h2)
return x1 < x2+w2 and
x2 < x1+w1 and
y1 < y2+h2 and
y2 < y1+h1
end
Code: Select all
hitboxes = {}
function hitboxes:update(dt)
--Gravity!
local collision = false --Right there
for i= 1, #block do
if collision then break end
collision = CheckCollision(player.x, player.y, 50, 50, block[i].x, block[i].y, 50, 50)
end
if collision == false then
player.y = player.y + 190*dt
end
end
That code should work, but you need to do collision checking for each axis to know which way your guy can't move. For example a lateral collision might stop you falling.