在有些地方我们会用到定时器,定时器分为两种,一种是隔多长时间调用一次的schedule(),一种是延时多长时间调用一次的unschedule()。两者用法基本相同,这里我们就只介绍第一种定时器的用法,我们实现每隔一秒钟在屏幕上随机位置打印“Hello”,这里用到一个随机数生成宏CCRANDOM_0_1(),随机生成一个0-1之间的数。
(注意:我使用的cocos2d-x版本是2.0.4,系统是win7)下载地址
首先我们修改HelloWorld.h函数如下,即添加了step()函数的声明和cocos2d命名空间的使用
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
#include "SimpleAudioEngine.h"
using namespace cocos2d;
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 recommand to return the exactly class pointer
static cocos2d::CCScene* scene();
// a selector callback
void menuCloseCallback(CCObject* pSender);
//定时器启动一次执行的函数
void step(float dt);
// implement the "static node()" method manually
CREATE_FUNC(HelloWorld);
};
#endif // __HELLOWORLD_SCENE_H__
接下来修改HelloWorld.cpp文件的init()函数,修改如下,只是删除了原来的背景,加入了定时器
bool HelloWorld::init()
{
bool bRet = false;
do
{
//////////////////////////////////////////////////////////////////////////
// super init first
//////////////////////////////////////////////////////////////////////////
CC_BREAK_IF(! CCLayer::init());
//////////////////////////////////////////////////////////////////////////
// add your codes below...
//////////////////////////////////////////////////////////////////////////
// 1. Add a menu item with "X" image, which is clicked to quit the program.
// Create a "close" menu item with close icon, it's an auto release object.
CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
this,
menu_selector(HelloWorld::menuCloseCallback));
CC_BREAK_IF(! pCloseItem);
// Place the menu item bottom-right conner.
pCloseItem->setPosition(ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20));
// Create a menu with the "close" menu item, it's an auto release object.
CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
pMenu->setPosition(CCPointZero);
CC_BREAK_IF(! pMenu);
// Add the menu to HelloWorld layer as a child layer.
this->addChild(pMenu, 1);
//定时器,参数代表:每次执行的方法,间隔时间
schedule(schedule_selector(HelloWorld::step), 1);
bRet = true;
} while (0);
return bRet;
}
然后只需要在HelloWorld.cpp文件中实现前面声明的step()函数即可,添加如下代码
void HelloWorld::step(float dt)
{
//取得屏幕大小
CCSize size=CCDirector::sharedDirector()->getWinSize();
//创建一行文本
CCLabelTTF* label=CCLabelTTF::create("Hello","Arial",30);
//CCRANDOM_0_1()是一个获取随机数的宏,随机产生一个0-1之间的数
float x=size.width * CCRANDOM_0_1();
float y=size.height * CCRANDOM_0_1();
//设置位置
label->setPosition(ccp(x,y));
//添加到布景
addChild(label);
}
运行程序,过几秒钟后,会出现如下效果
最后祝愿每一个奋斗在路上的人早日实现梦想!