如何在操作完成后运行方法

时间:2012-11-02 07:20:19

标签: objective-c cocos2d-iphone

我想知道如何在CCAction完成后调用方法(我还想在第一次调用后每隔2.5秒调用一次)。我有一个精灵进入一个随机位置,我希望它在完成移动到随机位置后运行这个方法(射击子弹一个)。到目前为止,该方法在仍在移动时被调用。有人可以帮忙吗?

这是敌人的创造方法:

(void)enemy1{
    gjk= arc4random()%6;
    enemy1 = [CCSprite spriteWithFile:@"enemy1.png"];

    int d = arc4random()%480+480;
    int o = arc4random()%320+320;
    x = arc4random()%480;
    if( x <= 480 && x>= 460){
        x=x-100;
    }
    if(x <= 100){
        x = x+50;
    }

    y = arc4random()%320;
    if(y <=320 && y >= 290){
        y = y-100;
    }
    if(y < 100){
        y = y + 100;
    }
    enemy1.position = ccp(o,d);
    [enemy1 runAction:[CCMoveTo actionWithDuration:3 position: ccp(x,y)]];
    CCRotateBy *rotation = [CCRotateBy actionWithDuration:20 angle:1080];
    CCRepeatForever * repeatforever = [CCRepeatForever actionWithAction:rotation];
    [enemy1 runAction:repeatforever];
    [self addChild:enemy1];
    [enemy addObject :enemy1];
}

拍摄射弹的方法:

(void)projectileShooting:(ccTime)dt {
    projcount++;
    if(enemy1.position.y < 320){
    v = ccp(player.position.x,player.position.y); 
    for(CCSprite *enemies in enemy){ 
        CCSprite * projectilebullet = [CCSprite spriteWithFile:@"Projectile.png"];
        [proj addObject:projectilebullet];
        [self addChild:projectilebullet];
        CGPoint MyVector = ccpSub(enemies.position,player.position );
        MyVector = ccpNormalize(MyVector);
        MyVector = ccpMult(MyVector, enemies.contentSize.width/2);
        MyVector = ccpMult(MyVector,-1);
        projectilebullet.position = ccpAdd(enemies.position, MyVector);
    }
}

通过代码在init方法中调用拍摄方法,因此每2.5秒调用一次。

 [self schedule:@selector(projectileShooting:) interval:2.5];

我知道我试图通过拍摄来实现拍摄,以便在 y 位置< 320,但是当它经过320的位置时仍然在移动。

2 个答案:

答案 0 :(得分:4)

您可以进行一系列操作,在序列结束时,您可以给出一个将在最后执行的回调函数。像这样的东西

[CCSequence actions:
        [CCMoveTo actionWithDuration:3 position: ccp(x,y)],
        [CCCallFunc actionWithTarget:self selector:@selector(methodToRunAfterAction)],
        nil]];

答案 1 :(得分:2)

再加上Tayyab的答案,您可以在 startShooting 方法(或任何您想要调用的方法)中开始实际安排射弹射击,这是在移动动作结束时触发的:

[CCSequence actions:
    [CCMoveTo actionWithDuration:3 position: ccp(x,y)],
    [CCCallFunc actionWithTarget:self selector:@selector(startShooting)],
    nil]];

其中 startShooting 的定义如下:

- (void) startShooting
{
    // start scheduling your projectile to fire every 2.5 seconds
    [self schedule:@selector(projectileShooting:) interval:2.5];
}
相关问题