一,游戏帧循环的理解
我们的游戏从main.cpp中的return CCApplication::sharedApplication()->run();
进入到applicationDidFinishLaunching() ;其中在一个死循环中调用了mainLoop(),mainLoop是CCDirector的一个纯虚函数,在CCDirector的子类CCDisplayLinkDirector中进行实现。mainLoop中
1, drawScene() //完成绘图功能
1)m_pRuningScene->visit(); //遍历当前运行的Scene中每个节点
2)m_pScheduler->update(m_fDeletatime); //完成定时功能
3)CCPoolmanager::sharedPoolManager()->pop(); //游戏中的autoRelease就是将内存放置到这个内存池中,而在内存池中每一次帧循环都会做检测,对计数为零的内存释放
通过1), 2), 我们可以说,动画的本质就是定时器加属性的改变
2,处理触摸消息
TranslateMessage(&msg); //完成对触摸消息的派发
DispatchMessage(&msg);
如此,我们的Cocos游戏的脉络已经很清晰了,通过mainLoop中每一帧的循环,每一帧都做以下几件事,也就是while中的
遍历渲染树中每一个节点,完成绘图;通过定时器完成定时功能;检查内存池中内存使用情况; 对触摸消息进行派发。
二,调度器的使用
2.1 什么是调度器?
顾名思义,定时器,就是一个“某个时刻运行”的东西,游戏中,按照时间比如每隔一段时间(这个时间单位一般都很小)对某个量进行检测(血量,位置等等)
调度器就是在指定时间间隔调用指定的函数,去完成特定的功能。
2.2 调度器的特点
2.2.1 每当Node(调度器是Node类的方法)不在可见或者已从场景中移除时,调度器会停止。也可以理解为该对象被回收掉了,所以对应的调度器也没有了作用。
2.2.2 Cocos2d-x暂停时,调度器也会停止。当Cocos2d-x重新开始时,调度器也会自动继续启动。
2.3 调度器的使用
在开发中,我们经常使用的有三种调度器
默认调度器 | scheduleUpdate() |
自定义调度器 | schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat, float delay) |
单词调度器 | scheduleOnce(SEL_SCHEDULE selector, float delay); |
/** 在node还在运行的场景下,如果调用了scheduleUpdate,该方法会在每一帧时,自动被调用*/virtual void update(float delta);
2.3.1 默认调度器(scheduleUpdate)
该方法实在每一帧绘制之前都会被调用
该调度器在内部会调用update方法,所以在使用的时候只需要override void update(float dt); 在update中填入我们自己的逻辑代码,当我们不在需要这个调度器时,使用unschedulerUpdate()方法,
代码示例
2.3.2 自定义调度器(schedule)
有时候我们并不需要每一帧都调度update方法,只需要在指定的时间间隔的情况下调用个函数。
解除该调度器用 2.3.3 单次调度器(scheduleOnce)
解除该调度器