假设我们面临一个需求:每隔一秒钟执行一次函数。不知各位看官会想怎么实现呢?我们可以利用cocos2d-x提供的schedule来解决。
我们新建一个项目为HelloSchedule,将HelloWorldScene的init函数的多余代码删除,然后改成如下几行代码:
bool HelloWorld::init()
{
if ( !CCLayer::init() )
{
return false;
}
this->scheduleUpdate();
return true;
}
还要记得在头文件中加入update函数的声明
class HelloWorld : public cocos2d::CCLayer
{
public:
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();
// there's no 'id' in cpp, so we recommend returning the class instance pointer
static cocos2d::CCScene* scene();
// implement the "static node()" method manually
CREATE_FUNC(HelloWorld);
/* 重写update函数 */
virtual void update(float dt);
};
然后在cpp文件中来具体实现这个