下面介绍如何在cocos2dx中实现一个时钟的功能。
其实实现很简单,获取到当前的时间,然后添加一个定时器,每隔一秒计时加一秒。
下面给出代码实现:
int nHour;
int nMinute;
int nSecond;
nHour = 0;
nMinute = 0;
nSecond = 0;
struct cc_timeval now;
CCTime::gettimeofdayCocos2d(&now, NULL);
struct tm* tm;
tm = localtime(&now.tv_sec);
nHour = tm->tm_hour;
nMinute = tm->tm_min;
nSecond = tm->tm_sec;
CCLog("%d -- %d -- %d",nHour,nMinute,nSecond);
this->schedule(schedule_selector(HelloWorld::timeUpdate), 1);
void HelloWorld::timeUpdate()
{
nSecond++;
if (nSecond==60) {
nSecond = 0;
nMinute++;
if (nMinute == 60) {
nMinute = 0;
nHour++;
if (nHour==24) {
nHour = 0;
}
}
}
CCLog("%d -- %d -- %d",nHour,nMinute,nSecond);
}
struct tm {
int tm_sec; /* seconds after the minute [0-60] */
int tm_min; /* minutes after the hour [0-59] */
int tm_hour; /* hours since midnight [0-23] */
int tm_mday; /* day of the month [1-31] */
int tm_mon; /* months since January [0-11] */
int tm_year; /* years since 1900 */
int tm_wday; /* days since Sunday [0-6] */
int tm_yday; /* days since January 1 [0-365] */
int tm_isdst; /* Daylight Savings Time flag */
long tm_gmtoff; /* offset from CUT in seconds */
char *tm_zone; /* timezone abbreviation */
};
运行上面的代码看看:
Cocos2d: 19 -- 9 -- 27
Cocos2d: 19 -- 9 -- 28
Cocos2d: 19 -- 9 -- 29
Cocos2d: 19 -- 9 -- 30
Cocos2d: 19 -- 9 -- 31
Cocos2d: 19 -- 9 -- 32
Cocos2d: 19 -- 9 -- 33
每隔一秒就输出当前的时间: 19点09分**秒