Page 1 of 1

how do i make a countdown timer?

Posted: Mon Jul 08, 2024 6:14 pm
by VXDev
im trying to make a timer to wait for my objects to spawn

plz help

heres my code:

Code: Select all

_G.love = require("love")



function love.load()
    listofRectangles = {}
    _G.game = {
        countdowntimer = 0
    }
    gamechart()
end

function love.update(dt)
        
    for i,v in ipairs(listofRectangles) do
        v.y = v.y + v.speed * dt
    end
end

function love.draw()
    for i,v in ipairs(listofRectangles) do
        love.graphics.rectangle("line", v.x, v.y, v.width, v.height)  
    end
end

function createRectangle()
    rectangle = {}
    rectangle.width =  50
    rectangle.height=  50
    rectangle.x     =  300
    rectangle.y     =  200
    rectangle.speed =  150
    return rectangle
end

function gamechart()
	-- heres where im trying to make it wait to spawn 
    table.insert(listofRectangles, createRectangle())
end

Re: how do i make a countdown timer?

Posted: Mon Jul 08, 2024 8:10 pm
by dusoft
If you want to use a library: https://github.com/airstruck/knife/blob ... e/timer.md

Otherwise it's simple, use delta time:
https://love2d.org/wiki/dt

Re: how do i make a countdown timer?

Posted: Mon Jul 08, 2024 9:50 pm
by togFox

Code: Select all


mytimer = mytimer + dt
if mytimer > 5 then
   -- do something
   mytimer = 0
end

Re: how do i make a countdown timer?

Posted: Tue Jul 09, 2024 7:13 am
by darkfrei

Code: Select all

local function newTimer(seconds, callback)
	return {
		duration = seconds,
		callback = callback,
		elapsedTime = 0,
		active = true
	}
end

local function updateTimer(timer, dt)
	if timer.active then
		timer.elapsedTime = timer.elapsedTime + dt
		if timer.elapsedTime >= timer.duration then
			timer.active = false
			timer.callback()
			return true -- true means: timer must be deleted
		end
	end
end