1. // There are two Sets
// Array Features: Low insertion and deletion efficiency, but high query efficiency
// List features: High insertion and deletion efficiency, but low query efficiency
// Analyze this game: when inserting: When a monster occurs, when a bullet occurs, when it is deleted: When a collision occurs, when a monster or a bounce occurs.
// Traversal: fps (number of frames filled with images per second (frame/second) corresponds to the time when a monster occurs once every two seconds, and traversal occurs 60 times per second, we can see that the traversal is mostly used, so we select array.
CCArray * _ targets; // defines a collection of monsters. Generally, 3.0 defines a set using a vector.
CCArray * _ projs; // defines a set of shells.
2. Set initialization and release
_ Targets = new CCArray;
_ Projs = new CCArray;
// In cocos2d, Class: create does not need to be manually released
// New needs to be released manually. We will release it in the destructor.
HelloWorld ::~ HelloWorld (){
If (_ targets! = NULL)
_ Targets-> release ();
If (_ projs! = NULL)
_ Projs-> release ();
}
3. Enable the update function (not activated by default)
This-> schedule (schedule_selector (HelloWorld: update); // enable the update function
4. traversal of a set:
Void HelloWorld: update (float dt) {// dt indicates the refresh cycle = 1/fps
CCObject * itarget;
CCObject * iproj;
CCArray * targetToDelect = new CCArray, therefore, we need to redefine the two sets to save, and remove and clear the collision targets and shells, and then traverse the two sets, so that the domain migration will not happen.
CCArray * projToDelect = new CCArray;
CCARRAY_FOREACH (_ targets, itarget) {// to facilitate the traversal of elements in the container, cocos2dx provides macros such as 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 );
}
} // Traverse monsters
} // Traverse the target
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 );
}
}