Page 1 of 1

Pixel Perfect Movement Problem [SOLVED]

Posted: Tue Sep 05, 2017 10:38 am
by ComplexMilkshake
Hello, I'm trying to create a grid based movement system for my game, but when using delta time, the pixel movement of the character goes a bit off. All the number are perfectly fine and round without delta time, but then the player moves too quickly.

So is there any way to get perfectly rounded numbers for movement with delta time.

Here is the current code:

Code: Select all

function love.load()
    player = {
        x = 0,
        y = 0,
        targetY = 0,
        targetX = 0,
        w = 16,
        h = 16,
        moving = false
    }
end

function love.update(dt)
    local left    = love.keyboard.isDown("left")
    local right   = love.keyboard.isDown("right")
    local up      = love.keyboard.isDown("up")
    local down    = love.keyboard.isDown("down")

    -- remove * dt to see the super quick movement
    if player.targetX > player.x then player.x = player.x + 4 * dt end
    if player.targetX < player.x then player.x = player.x - 4 * dt end
    if player.targetY > player.y then player.y = player.y + 4 * dt end
    if player.targetY < player.y then player.y = player.y - 4 * dt end

    if player.targetX == player.x and player.targetY == player.y then
        player.moving = false
    end

    if left and not player.moving then
        player.moving = true
        player.targetX = player.targetX - 16
    end
    if right and not player.moving then
        player.moving = true
        player.targetX = player.targetX + 16
    end
    if up and not player.moving then
        player.moving = true
        player.targetY = player.targetY - 16
    end
    if down and not player.moving then
        player.moving = true
        player.targetY = player.targetY + 16
    end
end

function love.draw()
    --love.graphics.scale(2)
    love.graphics.print(player.x, 0,0)
    love.graphics.print(player.y, 0, 10)

    love.graphics.rectangle("fill", player.x, player.y, player.w, player.h)
end
Thanks for any help :)

Re: Pixel Perfect Movement Problem

Posted: Tue Sep 05, 2017 11:05 am
by grump
Is the problem that your player position becomes non-integer values? You can round a number using either math.floor (rounds down) or math.ceil (rounds up). To round to the nearest integer value, use math.floor(number + 0.5).

Re: Pixel Perfect Movement Problem

Posted: Wed Sep 06, 2017 3:32 am
by ComplexMilkshake
Thanks, It now works perfectly! :)