1. Lets make the player moving smooth at any PC / at any FPS
use love.update(
dt)
I've added widths and heights to the player & wall.
Code: Select all
function love.load()
gameover = false
gamewin = false
player = {}
player.x = 100
player.y = 100
player.width = 20
player.height = 16
player.speed = 20
wall = {}
wall.x = 0
wall.y = 30
wall.width = 30
wall.height = 300
end
function love.update(dt)
player.sx = 0 --speed by X
player.sy = 0 --speed by Y
if love.keyboard.isDown("left") then
player.sx = -player.speed * dt
end
if love.keyboard.isDown("right") then
player.sx = player.speed * dt
end
if love.keyboard.isDown("up") then
player.sy = - player.speed * dt
end
if love.keyboard.isDown("down") then
player.sy = player.speed * dt
end
player.x = player.x + player.sx
player.y = player.y + player.sy
end
function love.draw()
--draw wall
love.graphics.setColor(127, 127, 64)
love.graphics.rectangle("fill", wall.x, wall.y, wall.width, wall.height)
--draw player
love.graphics.setColor(0, 255, 255)
love.graphics.rectangle("fill", player.x, player.y, player.width, player.height)
end
lets make your player check for collisions
Code: Select all
local 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
function love.load()
gameover = false
gamewin = false
player = {}
player.x = 160
player.y = 100
player.width = 20
player.height = 16
player.speed = 80
wall = {}
wall.x = 60
wall.y = 30
wall.width = 30
wall.height = 300
end
function love.update(dt)
player.sx = 0 --speed by X
player.sy = 0 --speed by Y
if love.keyboard.isDown("left") then
player.sx = -player.speed * dt
end
if love.keyboard.isDown("right") then
player.sx = player.speed * dt
end
if love.keyboard.isDown("up") then
player.sy = - player.speed * dt
end
if love.keyboard.isDown("down") then
player.sy = player.speed * dt
end
--use loops FOR to check it for many walls at once
--make some table... e.g. obstacles = {}
--then add all walls in there: obstacles[1] = wall; obstacles[2] = tree; etc
--add here a loop
--check collisions
if not CheckCollision(player.x + player.sx, player.y, player.width, player.height,
wall.x, wall.y, wall.width, wall.height)
then
player.x = player.x + player.sx
end
if not CheckCollision(player.x, player.y + player.sy, player.width, player.height,
wall.x, wall.y, wall.width, wall.height)
then
player.y = player.y + player.sy
end
end
function love.draw()
--draw wall
love.graphics.setColor(127, 127, 64)
love.graphics.rectangle("fill", wall.x, wall.y, wall.width, wall.height)
--draw player
love.graphics.setColor(0, 255, 255)
love.graphics.rectangle("fill", player.x, player.y, player.width, player.height)
end
this goes as yer homework
--use loops FOR to check it for many walls at once
--make some table... e.g. obstacles = {}
--then add all walls in there: obstacles[1] = wall; obstacles[2] = tree; etc
--add here a loop