Code: Select all
local map = {
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 1, 0},
{0, 0, 0, 0, 0},
{1, 1, 1, 1, 1},
}
local TILE_WIDTH = 8
local TILE_HEIGHT = 8
local player = {
x = 10,
y = 10,
w = 8,
h = 8,
speed = 50,
}
player.last = {
x = player.x,
y = player.y,
}
player.update = function(dt)
player.last.x, player.last.y = player.x, player.y
if love.keyboard.isDown("left") then
player.x = player.x - player.speed * dt
elseif love.keyboard.isDown("right") then
player.x = player.x + player.speed * dt
end
if love.keyboard.isDown("up") then
player.y = player.y - 100 * dt
end
player.y = player.y + 30 * dt
end
local col = function(x, y)
return player.x < x + TILE_WIDTH
and x < player.x + player.w
and player.y < y + TILE_HEIGHT
and y < player.y + player.h
end
local verticalAligned = function(y)
return player.last.y < y + TILE_HEIGHT and player.last.y + player.h > y
end
local horizontalAligned = function(x)
return player.last.x < x + TILE_WIDTH and player.last.x + player.w > x
end
map.update = function()
for y=1, #map do
for x=1, #map[1] do
local t = map[y][x]
local tileX = TILE_WIDTH * x - TILE_WIDTH
local tileY = TILE_HEIGHT * y - TILE_HEIGHT
if t == 1 then
if col(tileX, tileY) then
if verticalAligned(tileY) then
if player.x + player.w / 2 < tileX + TILE_WIDTH / 2 then
local pushback = player.x + player.w - tileX
player.x = player.x - pushback
else
local pushback = tileX + TILE_WIDTH - player.x
player.x = player.x + pushback
end
elseif horizontalAligned(tileX) then
if player.y + player.h / 2 < tileY + TILE_HEIGHT / 2 then
local pushback = player.y + player.h - tileY
player.y = player.y - pushback
else
local pushback = tileY + TILE_HEIGHT - player.y
player.y = player.y + pushback
end
end
end
end
end
end
end
function love.update(dt)
player.update(dt)
map.update()
end
function love.draw()
love.graphics.push()
love.graphics.scale(8)
for y=1, #map do
for x=1, #map[1] do
local t = map[y][x]
local tileX = TILE_WIDTH * x - TILE_WIDTH
local tileY = TILE_HEIGHT * y - TILE_HEIGHT
if t == 0 then
love.graphics.setColor(40, 40, 160)
elseif t == 1 then
love.graphics.setColor(40, 160, 40)
end
love.graphics.rectangle("fill", tileX, tileY, TILE_WIDTH, TILE_HEIGHT)
end
end
love.graphics.setColor(255, 255, 255)
love.graphics.rectangle("fill", player.x, player.y, player.w, player.h)
love.graphics.pop()
end