Hey there! I want to try to make a simple roguelike game, like Shiren The Wanderer. I want to make my character move grid for grid. And i thought about an implementation like this:
function love.load()
love.window.setTitle ('press WASD to move')
gridSize = 64
player = {
-- Initial grid position of the player
gridPos = {x=1, y=1},
-- Change in grid position (due to movement)
deltaGrid = {x=0, y=0},
-- Movement speed of the player (cells per second)
speed = 1,
-- Flag to track if the player is currently moving
moving = false,
}
end
function love.update(dt)
if player.moving then
-- Calculate movement distance for this frame
local delta = player.speed * dt
-- Adjust deltaGrid values based on direction of movement
if player.deltaGrid.x < 0 then
player.deltaGrid.x = math.min(0, player.deltaGrid.x + delta)
elseif player.deltaGrid.x > 0 then
player.deltaGrid.x = math.max(0, player.deltaGrid.x - delta)
end
if player.deltaGrid.y < 0 then
player.deltaGrid.y = math.min(0, player.deltaGrid.y + delta)
elseif player.deltaGrid.y > 0 then
player.deltaGrid.y = math.max(0, player.deltaGrid.y - delta)
end
-- Check if player has reached the target grid position
if player.deltaGrid.x == 0 and player.deltaGrid.y == 0 then
-- Player has stopped moving
player.moving = false
end
end
end
function love.draw()
-- Draw player's current position
love.graphics.setColor (0.5,0.5,0.5)
love.graphics.rectangle("fill",
(player.gridPos.x - 1)*gridSize,
(player.gridPos.y - 1)*gridSize,
gridSize, gridSize)
-- Draw player's interpolated position during movement
love.graphics.setColor (1,1,1)
love.graphics.rectangle("fill",
(player.gridPos.x - player.deltaGrid.x - 1)*gridSize,
(player.gridPos.y - player.deltaGrid.y - 1)*gridSize,
gridSize, gridSize)
end
function love.keypressed(key, scancode)
if key == "escape" then love.event.quit() end
if player.moving then return end
local scancodes = {
w = {x=0, y=-1},
a = {x=-1, y=0},
s = {x=0, y=1},
d = {x=1, y=0},
}
local deltaGrid = scancodes[scancode]
if deltaGrid then
print ('scancode', scancode, 'deltaGrid', deltaGrid.x, deltaGrid.y)
if player.deltaGrid.x == 0 then
player.deltaGrid.y = player.deltaGrid.y + deltaGrid.y
player.gridPos.y = player.gridPos.y + deltaGrid.y
end
if player.deltaGrid.y == 0 then
player.deltaGrid.x = player.deltaGrid.x + deltaGrid.x
player.gridPos.x = player.gridPos.x + deltaGrid.x
end
player.moving = true
end
end
@darkfrei thanks! I'll try it out
@BrotSagtMist before putting it into my handheld, i'm trying it out on https://replit.com/@Todespreis/PlasticG ... s#main.lua
But there were no response for pressing the buttons, so i thought, i did something wrong