枪在cocos2d射击

时间:2012-06-17 20:30:07

标签: ios xcode cocos2d-iphone

我刚刚开始学习iphone的Cocos2d编程,并对Cocos2d中的模仿拍摄有疑问。我有一个精灵。当我将它拖到另一个地方然后放下它时,我想开始用另一个名为 shell 的小精灵在一个方向上永久射击。所以我需要在-ccTouchesEnded中永远重复两步循环:

1. shell 开始远离精灵(模仿射击)(CCMoveTo);

2.当 shell 停止(它的移动范围有限)时,它应该消失或者应该变为不可见。(removeChild:,visible:或what?)

它需要永远重复(CCRepeatForever actionWithAction [CCSequence actions:];

所以,我需要帮助来设定这两个行动的永恒循环。

谢谢, 亚历克斯。

1 个答案:

答案 0 :(得分:1)

我真的不明白你在问什么。我会尽力帮助你理解我所知道的。

如果要删除shell,只需将它们设置为不可见。一直致电 addChild: removeChild:将导致您的设备失效。

相反,在游戏开始时,根据您的需要创建一个固定数量(可能是15 - 20)并将它们存储在一个数组中。将它们全部设为不可见。然后,每次需要shell时,获取一个未使用的shell,将其设置为可见,并对其应用操作。当你不再需要它时(当它停止时)只需将它设置为不可见。

如果你能详细说明一点,那么我很乐意尝试回答你的其余问题:)

编辑:

在.h文件中,创建一个名为shells的NSMutableArray。初始化它。创建一个int(bulletIndex = 0)然后在应用程序的开头调用:

- (void)createBullets {
    for (int i = 0; i < 15; i++) {
        CCSprite *shell = [CCSprite spriteWithFile:@"shell.png"]; //Create a sprite
        shell.visible = NO; //Set it invisible for now
        [self addChild:shell]; //Add it to the scene
        [shells addObject:shell]; //Add it to our array
    }
}

现在你的touchesEnded:方法:

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [self schedule:@selector(shootingTimer:) interval:1.0f]; //This schedules a timer that fires the shootingTimer: method every second. Change to fit your app
}

我们上面安排的方法:

- (void)shootingTimer:(ccTime)dt {
    CCSprite *shell = (CCSprite*)[shells objectAtIndex:bulletIndex]; //Get the sprite from the array of sprites we created earlier.
    shell.visible = YES; //Set it visible because we made it invisible earlier
    //Do whatever you want to with a shell. (Run your action)
    bulletIndex++; //Increment the index so we get a new shell every time this method is called
    if (bulletIndex > shells.count - 1) bulletIndex = 0; //We don't want to go out of our arrays (shells) bounds so we reset bulletIndex to zero if we go over
}

然后,如果你想在touchesBegan上关闭它:

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self unschedule:@selector(shootingTimer:)];
}

最后,就你的shell的动作而言,你将要做这样的事情:

id shellMove = [CCMoveTo actionWithDuration: yourDuration position: yourPosition]; //Move it to wherever you want
id shellEnd = [CCCallFuncN actionWithTarget: self selector:@selector(endShell:)]; //This will call our custom method after it has finished moving
id seq = [CCSequence actions:shellMove, shellEnd, nil]; //Create a sequence of our actions
[shell runAction:seq]; //Run the sequence action

endShell方法可能如下所示:

- (void)endShell:(id)sender {
    CCSprite *sprite = (CCSprite*)sender;
    sprite.visible = NO;
}

希望这解释了大多数(如果不是全部)问题。如果您需要进一步的帮助,请告诉我。