85
技術社區[雲棲]
cocos2dx 定時器(schedule)的使用及Label類的使用
首先在添加相應的方法聲明和成員變量聲明:
class HelloWorld : public cocos2d::Layer
{
public:
// there's no 'id' in cpp, so we recommend returning the class instance pointer
static cocos2d::Scene* createScene();
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();
// a selector callback
void menuCloseCallback(cocos2d::Ref* pSender);
// implement the "static create()" method manually
CREATE_FUNC(HelloWorld);
/// 下麵是需要我們添加的內容
// 每一幀會調用一次這個update方法,這個方法是繼承於父類的
virtual void update(float dt);
private:
//! 這個方法是私有方法,是我們自己添加的方法,不是繼承於父類的
void updateTimer(float dt);
private:
//! 在3.0後編碼風格不再采用m_加前綴的風格,而改為cocos2d的風格了,以下劃線開頭,不再添加前綴
cocos2d::Label *_label;
};
然後刪除實現文件中的init方法,我們自己寫一個:
// on "init" you need to initialize your instance
bool HelloWorld::init() {
if ( !Layer::init() ) {
return false;
}
// 創建一個標簽
// CCLabelTTF/LabelTTF已經在3.0rc1版本中丟棄了,現在找到了這個Label類來替換
_label = Label::create("BiaoGe", "Arial", 30);
_label->retain();
// 添加到層
addChild(_label);
// 啟動定時器,如果不打開,是不會調用update方法的,不過通常不會直接用這個方法
//scheduleUpdate();
// 這個方法需要四個參數
// 參數一:typedef void (Ref::*SEL_SCHEDULE)(float)
// 參數二:時間間隔,也就是每隔多少秒回調一次
// 參數三:重複執行的次數,也就是說執行多少次之後就自動關閉定時器,如果值為0,推薦使用scheduleUpdate方法,
// 如果要一直執行,使用kRepeatForever宏,重複執行的次數=inteval+1次
// 參數四:第一幀延時時長,也就是這個方法在被調用前延時1.5秒後再調用
schedule(schedule_selector(HelloWorld::updateTimer), 0.1, kRepeatForever, 0.5);
// 還有幾個重載版本的
// schedule(SEL_SCHEDULE selector, float interval)
// schedule(SEL_SCHEDULE selector)
return true;
}
再實現相應的定時器回調方法:
// 每一幀就會調用一次這個update方法,如果是使用scheduleUpdate打開的定時器,這個一幀的時間就是
// 幀率1/60.0,也就是每六十分之一秒就會調用一次這個方法
void HelloWorld::update(float dt) {
_label->setPosition(_label->getPosition() + Point(1, 1));
if (_label->getPositionX() >= 500) {
unscheduleUpdate(); // 關閉定時器
}
return;
}
// 使用 schedule(schedule_selector(HelloWorld::updateTimer), 0.1, kRepeatForever, 0.5)
// 打開的定時器,才會調用此方法
void HelloWorld::updateTimer(float dt) {
// 由於已經丟棄了ccpAdd這個宏,而且已經重載了Point類的+方法,可以直接使用+號,不需要再使用ccpAdd這個宏了
// 是不是更方便了!!!
_label->setPosition(_label->getPosition() + Point(4, 4));
if (_label->getPositionX() >= 500) {
unscheduleUpdate(); // 關閉定時器
}
return;
}
這樣是不是很簡單呢?嗬嗬,我覺得使用起來簡單多了,我也是菜鳥一枚,最近剛剛接觸cocos2dx,在學習過程中,喜歡把自己學習到的知識分享出來,
感興趣的,可以一起交流!!!
最後更新:2017-04-03 12:56:23