【Defold】カウントダウン処理を実装する

Defold, DEVELOP

local M = {}
 
function M.new()
	local instance = {}
 
	instance.handle = 0
	instance.countdown = 0
	instance.current_countdown = 0
 
	function instance.start(_countdown)
 
		instance.countdown = _countdown
		instance.current_countdown = _countdown
 
		if instance.handle then
			timer.cancel(instance.handle)
		end
 
		instance.handle = timer.delay(1, true, function()
 
			instance.current_countdown = instance.current_countdown - 1
			if instance.current_countdown <= 0 then
				timer.cancel(instance.handle)
			end
		end)
	end
 
	function instance.stop()
		if instance.handle then
			timer.cancel(instance.handle) 
		end
	end
 
 	
	function instance.get_countdown()
		return instance.current_countdown
	end
 
	return instance
end
 
return M

使い方

local countdown = require("配置場所.countdown")
 
-- 生成 
self.countdown = countdown.new()
 
-- カウントダウン開始
self.countdown.start(self.count_down_num)
 
-- カウント取得
self.countdown.get_countdown()

Posted by kazupon