Search code examples
lualove2d

Why does my lua script get different values each time I run it?


I have created a simple 2d scene in Love2D with a square that falls until it reaches a certain point and then stops. The problem is that the square stops at a slightly different point every time with no user input or modified code.

Here is my lua

function love.load()
    playY = 0
    playX = 10
    grav = 200
    speed = 100
end

function love.draw()
    --floor
    love.graphics.setColor(0,255,0,255)
    love.graphics.rectangle("fill", 0,465,800,150)
    --player
    love.graphics.setColor(255,255,0,255)
    love.graphics.rectangle("fill", playX,playY,10,10)
    --debug
    love.graphics.print(playY, 100, 5)
    love.graphics.print(playX, 100, 15)
end

function love.update(dt)
    if playY < 454 then 
        playY = playY + grav * dt
    end
    if playY == 456 then
        if love.keybord.isDown("right") then
            playX = playX + speed * dt
        end
    end
end

The variable playY shows the player height but it stops at different values every time.

enter image description here enter image description here enter image description here

Why is this?


Solution

  • As mentioned earlier dt is only as consistent as the games refresh rate. This value is multiplied with the velocity to give smooth gameplay.

    If this is a player and you wish the y to stop at 456, you can always write

    if playY > 456 then
        playY = 456
    end
    

    You can pretty much guarantee that the playY will stop at 456 every time because it will snap the player back to that spot.