cocos2dx Lua 定时器


Node类的scheduleUpdateWithPriorityLua方法


local MyLayer = class("MyLayer", function ()
	return cc.Layer:create()
end)


function MyLayer:ctor()
	--每帧都会调用,不能设置调用间隔
	self:scheduleUpdateWithPriorityLua(function(dt)
		self:update(dt)
		end, 0)
	--不能用scheduleUpdate方法?
	--error in function 'tolua_Cocos2d_Node_scheduleUpdateWithPriorityLua'.argument #2 is 'nil'; '[not function]' expected.
	--self:scheduleUpdate()
end

function MyLayer:update(dt)
	print(string.format("update------------------------------%sa", dt))
end

return MyLayer


测试输出


加入停止定时器部分

function MyLayer:update(dt)
	if self.runningTime== nil then
		self.runningTime = 0.0
	else
		self.runningTime = self.runningTime + dt
	end
	--10秒后停止定时器
	if self.runningTime > 10.0 then
		self:unscheduleUpdate()
		print("timer is end")
	else
		print(string.format("update------------------------------%s, %s", dt, self.runningTime))	
	end
	
end


scheduleScriptFunc启动定时器方式:


--另一种定时器实现
local TimerLayer2 = class("TimerLayer2", function()
		return cc.Layer:create()
	end)

--定时器回调方法,可配置周期
function TimerLayer2:timerHandler(dt)
	if self.runningTime== nil then
		self.runningTime = 0.0
	else
		self.runningTime = self.runningTime + dt
	end
	--10秒后停止定时器
	if self.runningTime > 10.0 then
		local scheduler=cc.Director:getInstance():getScheduler()
		--传入启动定时器时得到的entryID
		scheduler:unscheduleScriptEntry(self.scheduleScriptEntryID)
		print("timer is end")
	else
		print(string.format("timerHandler------------------------------%s, %s", dt, self.runningTime))	
	end
end

function TimerLayer2:ctor()
	--启动定时器
	local scheduler=cc.Director:getInstance():getScheduler()
	--第三个参数:If paused is true, then it won't be called until it is resumed.
	--返回值是一个entryId,停止定时器要用到
	self.scheduleScriptEntryID = scheduler:scheduleScriptFunc(function(dt)
			self:timerHandler(dt)
		end,2,false)
end

return TimerLayer2








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值