cocos2d-x 帧循环不严谨造成场景切换卡顿

  最近在用cocos2d-x做引导界面,2dx版本是2.2.3,场景切换加上了效果,所有资源都已经使用texturepacker打包预加载,但是在实际运行调试中,场景切换相当卡顿。

  各种纠结后,无意中将帧率打印(setDisplayStats(true))放出来,发现一个严重的问题,对象数量一直在增加,导致帧率不断下降,等到场景切换时,已经完全跑不动了。仔细查看代码之后发现,我在场景帧循环(update())里面有监控手机网络状态,并且根据网络状态需要移除一些精灵,然后创建一些精灵并显示出来,问题就在这里。

void SkyGuideSecondPage::update(float delta)
{
    char wlan_state[16] = {0};
    property_get("coocaa.wlan_state", wlan_state, "0");int wlanstate = atoi(this->guideinfo.wlan_state);

    if (wlanstate == 1)
    {
  this->removeChildByTag(214);
       CCSprite *sp_connecting = CCSprite::createWithSpriteFrame(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("guide_connecting_ttf"));
       sp_connecting->setAnchorPoint(ccp(0, 1));
       sp_connecting->setPosition(ccp(1640, 1750));
       sp_connecting->setScale(1.5f);
       this->addChild(sp_connecting);
    //如果wlanstate在某一时刻开始等于1了,那么将会从这一帧起,每一帧创建一个sp_connecting精灵,一秒帧循环40次,那么每秒就创建了40个相同的精灵,哗啦啦的各种消耗上来了,再场景切换,肯定卡了,所以在这里需要加一个状态判断,保证sp_connecting只创建一次就好了。
}

修改后的代码:

void SkyGuideSecondPage::update(float delta)
{
    char wlan_state[16] = {0};
    property_get("coocaa.wlan_state", wlan_state, "0");
    int wlanstate = atoi(this->guideinfo.wlan_state);

    if (wlanstate == 1)
    {
        if (this->connectflag == 0)//初始状态为0,状态判断
        {
            this->connectflag = 1;//将状态置1,这样下一帧就进不来了,精灵sp_connecting就不会再次被创建了
            this->removeChildByTag(214);
            CCSprite *sp_connecting = CCSprite::createWithSpriteFrame(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName("connecting"));
            sp_connecting->setAnchorPoint(ccp(0, 1));
            sp_connecting->setPosition(ccp(500, 400));
            sp_connecting->setScale(1.5f);
            this->addChild(sp_connecting);
        }
}
原文地址:https://www.cnblogs.com/leisc/p/3967852.html