头文件
#pragma once
#include "cocos2d.h"
USING_NS_CC;
enum class jishiqi_type
{
jishi_start = 0,//计时器开始
jishiqi_ing,//正在计时,每秒刷新
jishiqi_end//计时器时间到了
};
class jishiqi:public Node
{
public:
//全局计时器,计时方法可以根据需求在修改
static jishiqi* createForverJishiqi(int fen, int miao, std::function<void(jishiqi*, jishiqi_type)> callback);
static void destroyInstance();
public:
//非全局计时器
static jishiqi* create(int fen, int miao, std::function<void(jishiqi*, jishiqi_type)> callback);
void resetTime(int fen,int miao);
private:
bool initJishiqi(int fen, int miao, std::function<void(jishiqi*, jishiqi_type)> callback);
void timeUpdate(float f);
void firstTimeUpdate();//第一次计时器响应,用于初始化显示
private:
CC_SYNTHESIZE_READONLY(int ,fen,Fen);
CC_SYNTHESIZE_READONLY(int ,miao,Miao);
std::function<void(jishiqi*, jishiqi_type)> m_callback;;
static jishiqi * instance;
};
源文件
#include "jishiqi.h"
jishiqi * jishiqi::instance = nullptr;
jishiqi* jishiqi::createForverJishiqi(int fen, int miao, std::function<void(jishiqi*, jishiqi_type)> callback)
{
if (instance == nullptr)
{
instance = jishiqi::create(fen, miao, callback);
instance->retain();
}
else
{
instance->m_callback = callback;
instance->resetTime(fen,miao);
}
return instance;
}
void jishiqi::destroyInstance()
{
CC_SAFE_DELETE(instance);
}
jishiqi* jishiqi::create(int fen, int miao, std::function<void(jishiqi *, jishiqi_type)> callback)
{
jishiqi *g_jishiqi=new jishiqi;
if (g_jishiqi->initJishiqi(fen, miao, callback))
{
g_jishiqi->autorelease();
return g_jishiqi;
}
delete g_jishiqi;
return NULL;
}
void jishiqi::resetTime(int fen, int miao)
{
this->fen = fen;
this->miao = miao;
this->firstTimeUpdate();
this->schedule(schedule_selector(jishiqi::timeUpdate), 1);
}
bool jishiqi::initJishiqi(int fen, int miao, std::function<void(jishiqi*, jishiqi_type)> callback)
{
this->fen = fen;
this->miao = miao;
this->m_callback = callback;
this->schedule(schedule_selector(jishiqi::timeUpdate),1);
this->firstTimeUpdate();
return true;
}
void jishiqi::timeUpdate(float f)
{
if(this->miao==0)
{
if(fen>0)
{
this->fen--;
this->miao=59;
}
else
{
(this->m_callback)(this, jishiqi_type::jishiqi_end);//计时器回到零
this->unschedule(schedule_selector(jishiqi::timeUpdate));
return;
}
}
else
this->miao--;
(this->m_callback)(this, jishiqi_type::jishiqi_ing);
}
void jishiqi::firstTimeUpdate()
{
(this->m_callback)(this, jishiqi_type::jishi_start);
}
使用很简单
jishiqi * jishi = jishiqi::create(0, 20, CC_CALLBACK_2(HelloWorld::jishicallback, this));
this->addChild(jishi);
……
void HelloWorld::jishicallback(jishiqi* g_jishiqi, jishiqi_type type)
{
switch (type)
{
case jishiqi_type::jishi_start:
break;
case jishiqi_type::jishiqi_ing:
break;
case jishiqi_type::jishiqi_end:
break;
default:
break;
}
}
我大概是一叶障目了。。。
jishiqi类的timeUpdate没有响应,请问为什么?