Qwertie
Qwertie

Reputation: 6493

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?

Upvotes: 0

Views: 170

Answers (2)

compulsivestudios
compulsivestudios

Reputation: 91

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.

Upvotes: 1

Oliver
Oliver

Reputation: 29463

I haven't used love2d so I could be totally wrong, but based on my experience with various GUI: my guess is that Love2d handles these calls in an idle event loop so you are not guaranteed that the time steps are constant or the same every time you run your program, this will cause the sequence of positions to be different every time (print them, you'll see). Unless love2d has a timer function that has fairly good accuracy regardless of what is happening in the GUI (would be surprising), you'll have to be content with the accuracy (0.5%, not bad) that love2d supports. This means you can't use conditions like if something == 456 because you might miss it, better use a range.

Upvotes: 2

Related Questions