cocos2d按顺序在不同的目标上运行序列

时间:2012-06-14 14:20:37

标签: objective-c cocos2d-iphone

所以,我有一个基本的游戏场景:

有些单位移动靠近敌方单位,射击弹丸,然后调整敌方单位的生命。我的问题是我不知道如何安排这三个事件一个接一个地运行。如果所有这些操作都是在同一个目标上完成的,那么这将非常简单,但有两个不同的目标。

这样做的最佳方法是什么?

代码如下所示:

Unit* unit = [self getActiveUnit];
Unit* enemy = [self getEnemyInRange:unit];

CGpoint A = unit.sprite.position;
CGPoint B = [self getPositionClose:enemy for:unit];

CCSequence* unitMove = [self generateUnitMoveFrom:A to:B];

Projectile* proj = [self generateProjectile];
CCSequence* projMove = [self generateProjMoveFrom:A to:B];

CCSequence* attackDone = [self generateAttackDoneFor:unit enemy:enemy];

// This is the part that i don't know how to do
// Execute these in order and sequentially, not at the same time
[unit.sprite runAction:unitMove];
[proj.sprite runAction:projMove];
[proj.sprite runAction:removeSprite];
[self runAction:attackDone];

这样做的最佳方法是什么?即使使用CCActionManager,它仍然看起来相当复杂,因为我认为我必须在所有这些操作之间添加额外的回调以恢复下一个目标的计划操作。

有什么想法吗?

谢谢!

4 个答案:

答案 0 :(得分:4)

我会尝试使用CCSequence

[self runAction:[CCSequence actions:
  [CCCallFuncO actionWithTarget:unit.sprite selector:@selector(runAction:) object:unitMove],
  [CCCallFuncO actionWithTarget:proj.sprite selector:@selector(runAction:) object:projMove],
  [CCCallFuncO actionWithTarget:proj.sprite selector:@selector(runAction:) object:removeSprite],
  [CCCallFunc actionWithTarget:self selector:@selector(attackDone)],
                     nil]];

答案 1 :(得分:2)

您可能需要此代码才能运行多个CCAction针对不同CCNode / CCSprite /...的每个操作);但是按顺序启动所有

CCMoveBy *moveUpAction = CCMoveBy::create(0.5,ccp(0,400));
CCMoveBy *moveRightAction = CCMoveBy::create(1,ccp(300,0));
CCMoveBy *moveDownAction = CCMoveBy::create(1,ccp(0,-400));

CCTargetedAction *mm = CCTargetedAction::create(someNode_1,moveUpAction);
CCTargetedAction *rr = CCTargetedAction::create(someNode_2,moveRightAction);
CCTargetedAction *dd = CCTargetedAction::create(someNode_3,moveDownAction);

// Here we first run 'moveUpAction' on someNode_1.
// After finishing that Action we start 'moveRightAction' on someNode_2
// After finishing the Action, we start ...
CCSequence *targetedSeq = CCSequence::create(mm,rr,dd,NULL);
whateverNode->runAction(targetedSeq );

答案 2 :(得分:1)

同意詹姆斯的观点。另外,如果有一些动作你想要在其他人运行之前给予更多时间,你可以加上延迟......

  

[CCDelayTime actionWithDuration:0.5];

答案 3 :(得分:1)

你可以创建一个你的动作数组,然后调用一些方法来逐个调用它们。例如

- (void) playManyActionsOneByOne
{
    // create some actions and add them to the
    // mutable array m_actionsContainer

    [self runNextActionInArray];
}

- (void) runNexActionInArray
{
    if( [m_actionsContainer count > 0] )
    {
        id nextAction = [m_actionsContainer objectAtIndex:0];
        id callback = [CCCallFunc actionWithTarget: self selector: @selector(runNextActionInArray)];
        id sequence = [CCSequence actionOne: nextActon two: callback];
        [neededNode runAction: sequence];

        [m_actionsContainer removeObjectAtIndex:0];
    }    
}

它将逐个运行操作,您甚至可以在其他操作尚未完成的情况下向您的阵列添加操作。