0

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?

2
  • No user input? this: love.keybord.isDown("right") seems to suggest otherwise. Commented May 10, 2014 at 8:39
  • By no user input I mean I haven't touched the keyboard. Commented May 10, 2014 at 8:40

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.