cocos2dx 定时器(schedule)的使用及Label类的使用

来源:互联网 发布:男士 爽肤水 知乎 混合 编辑:程序博客网 时间:2024/05/16 03:13

首先在添加相应的方法声明和成员变量声明:

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 instancebool 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,在学习过程中,喜欢把自己学习到的知识分享出来,

感兴趣的,可以一起交流!!!


0 0
原创粉丝点击