Random Timer

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
Oblivion_123
Prole
Posts: 18
Joined: Thu Oct 01, 2015 5:25 pm

Random Timer

Post by Oblivion_123 » Sat May 07, 2016 5:52 pm

I want to make a timer so that every minute or so it could do something else. What is it that I want it to do is irrelevant however, I would like to know if it is possible to make a timer that could do something when the timer ends.

Any help is much appreciated,
Thanks!

User avatar
pgimeno
Party member
Posts: 1909
Joined: Sun Oct 18, 2015 2:58 pm
Location: Valencia, ES

Re: Random Timer

Post by pgimeno » Sat May 07, 2016 7:49 pm

Sure! You can have a function like this:

Code: Select all

local function timer_end()
  local rand = love.math.random(1, 5) -- 5 possible things to do in this example
  if rand == 1 then
    -- do thing #1
  elseif rand == 2 then
    -- do thing #2
  elseif rand == 3 then
    -- do thing #3
  elseif rand == 4 then
    -- do thing #4
  else
    -- do thing #5
  end
end
If you use a timer library which accepts a callback function, you would pass it timer_end as the callback.

If you don't, you can make your own timer using a variable, with something like this:

Code: Select all

local timer_period = 60 -- time in seconds of each timer tick, 60 means 1 minute
local timer = timer_period

function love.update(dt)
  timer = timer - dt
  if timer <= 0 then
    timer_end() -- call the callback
    timer = timer + timer_period
  end
end

Oblivion_123
Prole
Posts: 18
Joined: Thu Oct 01, 2015 5:25 pm

Re: Random Timer

Post by Oblivion_123 » Sat May 07, 2016 8:07 pm

Cheers dude, thanks a lot for the help!

Post Reply

Who is online

Users browsing this forum: No registered users and 9 guests