cocos2d基础篇笔记四

来源:互联网 发布:鞍山plc编程培训 编辑:程序博客网 时间:2024/05/17 02:15

1.//有两种集合

//第一种是array 特点:插入,删除效率低,但是查找效率高

//第二种是list  特点:插入,删除效率高,但是查找效率低

//分析这个游戏: 插入的时候:怪物,射弹出现时,删除的时候:碰撞时,怪物、射弹出界时。
//遍历:fps(每秒中填充图像的帧数(帧/秒)对应的时间,怪物是2秒出现一次,而遍历是60次每秒,可见遍历用的较多,所以我们选择array。
CCArray*_targets;//定义怪物集合,3.0一般用vector定义集合
CCArray*_projs;//定义射弹集合

2.集合的初始化和释放

_targets=new CCArray;

_projs=new CCArray;
//cocos2d中Class:create不需要手动释放

//new需要手动释放,我们把它放在析构函数释放。

HelloWorld::~HelloWorld(){
if(_targets!=NULL)
_targets->release();
if(_projs!=NULL)
_projs->release();
}

3.开启update函数(默认是没激活的)

this->schedule(schedule_selector(HelloWorld::update));//开启update函数

4.集合的遍历:

void HelloWorld::update(float dt){                                               //dt为刷新周期=1/fps
CCObject*itarget;
CCObject*iproj;
CCArray*targetToDelect=new CCArray;                         //如果当有交集时就直接从容器移除并且清楚靶子或者射弹会导致下次遍历越域,因此我们重新定义两个集合来保                                                                                                               存,发生碰撞的靶子和射弹,然后在遍历这两个集合在进行移除和清理,就不会发生越域的情况。
CCArray*projToDelect=new CCArray;                            
CCARRAY_FOREACH(_targets,itarget){                           //为了方便遍历容器里面的元素,cocos2dx提供了CCARRAY_FOREACH这样的宏
CCSprite*target=(CCSprite*)itarget;
CCRect targetZone=CCRectMake(target->getPositionX(),
target->getPositionY(),
target->getContentSize().width,
target->getContentSize().height);


CCARRAY_FOREACH(_projs,iproj){
CCSprite*proj=(CCSprite*)iproj;
CCRect projZone=CCRectMake(proj->getPositionX(),
proj->getPositionY(),
proj->getContentSize().width,
proj->getContentSize().height);


if(projZone.intersectsRect(targetZone)){
targetToDelect->addObject(itarget);
projToDelect->addObject(iproj);
}
}                                                              //遍历怪物
}                                                                     / /遍历靶子
CCARRAY_FOREACH(targetToDelect,itarget){
_targets->removeObject(itarget);
CCSprite*target=(CCSprite*)itarget;
target->removeFromParentAndCleanup(true);
}
CCARRAY_FOREACH(projToDelect,iproj){
         _projs->removeObject(iproj);
CCSprite*proj=(CCSprite*)iproj;
proj->removeFromParentAndCleanup(true);
}


}

0 0
原创粉丝点击