首先写一个计时器的头文件GameTimer.h:
#ifndef _GAME_TIMER_H_ #define _GAME_TIMER_H_
#include "cocos2d.h"
class GameTimer : public cocos2d::Node { public: GameTimer();
virtual ~GameTimer();
static GameTimer* createTimer(float time);
void update(float delta);
bool init(float time);
void stop();
float getTime();
private: cocos2d::LabelTTF* label; float pTime; };
#endif
GameTimer.cpp如下:
#include "GameTimer.h"
USING_NS_CC;
GameTimer::GameTimer() {
}
GameTimer::~GameTimer() {
}
bool GameTimer::init(float time) {
pTime = time;
label = LabelTTF::create();
label->setPosition(ccp(130, 610));
this->addChild(label);
schedule(schedule_selector(GameTimer::update));
return true; }
void GameTimer::stop() {
this->unschedule(schedule_selector(GameTimer::update));
}
float GameTimer::getTime() {
return pTime;
}
void GameTimer::update(float delta) {
pTime -= delta;
char* mtime = new char[10];
//此处只是显示分钟数和秒数 自己可以定义输出时间格式
sprintf(mtime, "%02d : %02d", (int)pTime / 60, (int)pTime % 60);
label->setString(mtime);
label->setFontSize(30);
label->setColor(Color3B(0, 0, 0));
}
GameTimer* GameTimer::createTimer(float time) {
GameTimer* gametimer = new GameTimer;
if (gametimer && gametimer->init(time)) {
gametimer->autorelease(); return gametimer;
}
else {
delete gametimer; gametimer = NULL;
}
return NULL;
}
在MyGame.h中声明:
头文件#include "GameTimer.h"
函数void Updatetime(float t);//该函数用于让计时器停止计时
MyGame.cpp:
#include "MyGame.h"
#include "cocostudio/CocoStudio.h"
#include "ui/CocosGUI.h"
#include "cocos2d.h"
#include "GameTimer.h"
#include<iostream>
#include<stdio.h>
using namespace std;
USING_NS_CC;
using namespace cocos2d;
using namespace cocostudio::timeline;
Scene* MyGame::createScene() {
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = MyGame::create();
// add layer as a child to scene scene->addChild(layer);
// return the scene return scene;
}
bool MyGame::init()
{
//////////////////////////////
// 1. super init first
if (!Layer::init())
{
return false;
}
//创建计时器
m_timeCounter = GameTimer::createTimer(61); this->addChild(m_timeCounter);
//开始计时
m_timeCounter->init(61);
this->schedule(schedule_selector(MyGame::Updatetime));
// 创建背景图片
auto dirt = Sprite::create("scene.png");
dirt->setScaleX(0.75);
dirt->setScaleY(0.803);
dirt->setAnchorPoint(Vec2::ZERO);
dirt->setPosition(0, 0);
this->addChild(dirt, -2);
.....................
return true;
}
//Updatetime函数
void MyGame::Updatetime(float t)//超过60秒,让时间暂停
{
if (m_timeCounter->getTime() <= 0) m_timeCounter->stop();
}
运行结果如下: