Working Timer

I have been trying to get a Timer working to make my own mission. I have looked at the other missions and found this code as a timer.


mission_timer = 40
mission_timer = mission_timer - delta
if mission_timer == 0 then

end


When I use that on my own code it does not work. I printed the value of mission_timer out and instead of going down from the original it just lingers going up and down and never reaches the value it should(0 in this case). Can someone explain to me how to make a timer or how delta is used? Thanks.

Comments

  • edited December 2017
    First off, if you have the "mission_timer = 40" in the update function, it will reset the timer value to 40 every single update, so nothing will change there.

    Next, the "delta" parameter of the update function is the time difference between this call and the previous. For example, if the game is running at 60FPS, the delta value will be "0.0166".

    Next, you will never reach exactly 0. If you look closely at the other code, it never uses "== 0", it uses "< 0". The reason for that is simple. Imagine the delta being exactly 0.0166. After 2409 calls to update, the remaining value in the timer is "0.0106", once we subtract 0.0166 from that, we have "-0.006", which is also not zero. It's close to zero, but not zero.


    The timer from the "waves" scenario might be a good example, simplified a bit:
    function init()
    spawnWaveDelay = 10
    end

    function update(delta)
    if spawnWaveDelay ~= nil then
    spawnWaveDelay = spawnWaveDelay - delta
    if spawnWaveDelay < 0 then
    spawnWaveDelay = nil
    spawnWave()
    end
    end
    end
    This is a basic "single shot" timer, it's started when the "init" function is ran, and after 10 seconds it runs the spawnWave function. Then it sets the "spawnWaveDelay" to "nil" (which is a special value for saying that it has no value anymore) which stops the timer.

    You could put it to a value instead of nil to make a repeating timer.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!