Cocos2d-x lua中的定时器
来源:互联网 发布:国外开源cms 编辑:程序博客网 时间:2024/05/17 23:39
定时器用的地方还是比较多的,游戏中的逻辑判断很多都是采用每帧执行。quick对于schedule的封装在scheduler这个lua文件中。如果是第一次接触quick的话,可能按照官方的api来写一个定时器被报错,提示schedule是一个nil值,这是因为其他的模块在初始化时都是被加载的,唯独这个scheduler没有载入,所以在使用的时候,第一件事是引入这个模块,
- local scheduler = require("framework.scheduler")
每帧调用的,
void scheduleUpdateWithPriority (int priority)
void scheduleUpdateWithPriorityLua (int nHandler,int priority)
指定调用间隔时间的,
unsigned int scheduleScriptFunc (unsigned int nHandler, float fInterval, bool bPaused)
还有取消定时器事件
void unscheduleScriptEntry (unsigned int uScheduleScriptEntryID)
quick的scheduler主要是对后面两个函数的封装。在c++的cocos使用中,我们使用定时器,无非就是每帧调用,间隔时间调用无数次,间隔时间调用指定次数,间隔时间调用一次,取消调用这几个。
我们依次来看下,
每帧调用,
- local time = 0
- local function update(dt)
- time = time + 1
- label:setString(string.format("%d", time))
- end
- scheduler.scheduleUpdateGlobal(update)
间隔一定时间调用,
- local time = 0
- local function onInterval(dt)
- time = time + 1
- label:setString(string.format("%d", time))
- end
- scheduler.scheduleGlobal(onInterval, 1)
- local time = 0
- local function onInterval(dt)
- time = time + 1
- label:setString(string.format("%d", time))
- print("over")
- end
- scheduler.performWithDelayGlobal(onInterval, 1)
可以看下这个是怎么实现的,
- function scheduler.performWithDelayGlobal(listener, time)
- local handle
- handle = sharedScheduler:scheduleScriptFunc(function()
- scheduler.unscheduleGlobal(handle)
- listener()
- end, time, false)
- return handle
- end
其实就是在间隔一定时间后,将其停止,然后执行一次回调函数就可以了。
封装的最后一个是停止这些定时器,
- scheduler.unscheduleGlobal()
它的参数是前面那些定时器返回的句柄,所以如果需要在后面停止掉,记得在创建的留一个返回值就好了。
不过在游戏中,我们可能会做一个倒计时,也就是间隔一定时间调用指定的次数,这个是在quick中没有封装的,但是我们还是可以自己动手实现一下,原理也很简单,每次执行一次就计个数,达到指定的次数就停止定时器,
- local handle
- local interval = 1
- local repeatIndex = 3
- local index = 0
- local sharedScheduler = CCDirector:sharedDirector():getScheduler()
- handle = sharedScheduler:scheduleScriptFunc(function()
- index = index + 1
- label:setString(string.format("%d", index))
- if index >= repeatIndex then
- scheduler.unscheduleGlobal(handle)
- print("over")
- end
- end, interval, false)
效果如图
定时器就是这样子了。
http://blog.csdn.net/w337198302/article/details/38677971
- Cocos2d-x lua中的定时器
- Cocos2d-x 3.x lua中的定时器
- Cocos2d-x 3.0 lua中的定时器
- cocos2d-x lua 定时器
- Cocos2d-x lua 使用定时器
- cocos2d-x中的lua调试
- Cocos2d-x学习(4) - cocos2d-x中的定时器
- lua使用cocos2d-x中的函数
- Cocos2d-x 脚本语言Lua中的面向对象
- Cocos2d-x 脚本语言Lua中的面向对象
- Cocos2d-x 3.0 中的lua binding - fonzieyang
- cocos2d-x Lua 中的公共函数 handler
- cocos2d-x schedule 定时器
- cocos2d-x 定时器 schedule
- COCOS2D-X全局定时器
- cocos2d-x 定时器 schedule
- cocos2d-x schedule 定时器
- cocos2d-x定时器
- Android 搜索框的实时查询/模糊查询
- 分解质因数 欧拉函数
- 读书笔记《Lua设计与实现》 了解Lua底层
- python中的argsort()函数
- 在win7下安装biolinux虚拟机
- Cocos2d-x lua中的定时器
- C语言操作符总结
- 2017长乐国庆欢乐赛Day1
- 剑指offer--替换空格
- dinic 最大流模板
- 习题7-7:埃及分数(迭代加深)
- error LNK2019无法解析的外部符号解决方案 && error LNK1120: 1 个无法解析的外部命令
- 51nod_数字1的数量
- JAVA提高篇(30)--Map接口