Cocos2d-x 实现时钟

来源:互联网 发布:美微网络电视看香蕉 编辑:程序博客网 时间:2024/05/19 02:23

下面介绍如何在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);}


在上面的代码中只是输出了小时,分钟和秒数。其实注意到tm这个结构体:(还包含着其他的时间

struct tm {inttm_sec;/* seconds after the minute [0-60] */inttm_min;/* minutes after the hour [0-59] */inttm_hour;/* hours since midnight [0-23] */inttm_mday;/* day of the month [1-31] */inttm_mon;/* months since January [0-11] */inttm_year;/* years since 1900 */inttm_wday;/* days since Sunday [0-6] */inttm_yday;/* days since January 1 [0-365] */inttm_isdst;/* Daylight Savings Time flag */longtm_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分**秒

原创粉丝点击