我正在为 iPhone 使用 Cocos2d,我想知道使用这种方法构建我的代码逻辑以产生敌人是否更有效:
-(void) schedule:(SEL)selector interval:(ccTime)interval
或在 EnemyCache 类中使用更新,并每次验证是否满足时间间隔。下面是在 EnemyCache 类的 update 方法中调用的代码片段(相对时间是一个整数值,在 GameScene 类中每次更新时由 GameScene 更新 - GameScene 更新方法调用以 1 的间隔调度第二):
-(void) checkForPlayerCollisionsAndSpwanTime
{
int count = [elements count];
//CCLOG(@"count %i", count);
Element* element;
for(int i=0; i<count;i++){
element = [elements objectAtIndex:i];
NSAssert(element!=nil, @"Nil enemy");
if (element.visible)
{
[element justComeDown];
ShipEntity * ship = [[GameScene sharedGameScene]defaultShip];
CGRect rect = [ship boundingBox];
if (CGRectIntersectsRect([element boundingBox], rect)){
[element doWhatever];
element.visible=FALSE;
[element stopAllActions];
}
}
else{
if(element.spawnTime == relativeTime) {
[self addChild:element];
element.visible=TRUE;
}
}
}
}
不同之处在于,在每次更新时,checkForPlayerCollisionsAndSpwanTime方法都会通过敌人数组。第一种方式,通过调度一个选择器调用类似的方法,可以减少CPU查看数组和条件的时间。
我不确定这个电话的成本有多大:
[self schedule:selector interval:interval repeat:kCCRepeatForever delay:0];
通过查看,我看到调用了这个方法(见下文),但我想问一下你解决这个问题的方法是什么,以及我是否应该继续使用 EnemyCache 更新方法或使用 scheduleSelector 方法。
-(void) scheduleSelector:(SEL)selector forTarget:(id)target interval:(ccTime)interval paused:(BOOL)paused repeat:(uint) repeat delay:(ccTime) delay
{
NSAssert( selector != nil, @"Argument selector must be non-nil");
NSAssert( target != nil, @"Argument target must be non-nil");
tHashSelectorEntry *element = NULL;
HASH_FIND_INT(hashForSelectors, &target, element);
if( ! element ) {
element = calloc( sizeof( *element ), 1 );
element->target = [target retain];
HASH_ADD_INT( hashForSelectors, target, element );
// Is this the 1st element ? Then set the pause level to all the selectors of this target
element->paused = paused;
} else
NSAssert( element->paused == paused, @"CCScheduler. Trying to schedule a selector with a pause value different than the target");
if( element->timers == nil )
element->timers = ccArrayNew(10);
else
{
for( unsigned int i=0; i< element->timers->num; i++ ) {
CCTimer *timer = element->timers->arr[i];
if( selector == timer->selector ) {
CCLOG(@"CCScheduler#scheduleSelector. Selector already scheduled. Updating interval from: %.4f to %.4f", timer->interval, interval);
timer->interval = interval;
return;
}
}
ccArrayEnsureExtraCapacity(element->timers, 1);
}
CCTimer *timer = [[CCTimer alloc] initWithTarget:target selector:selector interval:interval repeat:repeat delay:delay];
ccArrayAppendObject(element->timers, timer);
[timer release];
}