Search code examples
iphonecocos2d-iphoneccsprite

Implementing Touches on Multiple CCSprites in Cocos2d the right way??


I am developing my first game with cocos2d and i have run into a problem of which i cant seem to find a right solution. i am adding and animating a CCSprite every second from top of the screen to the bottom and need to hide these sprites when the player touches on any one of them. So i thought of giving tags to every sprite i add and later on access that sprite with that particular tag. Do i need to put the tag number in some array as they get incremented every second even before i access them in the touch method??

- (void)addStraightBugs 
{
currentAntTag++;

[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"smallAunt.plist"];        

spriteSheetmedAnt = [CCSpriteBatchNode batchNodeWithFile:@"smallAunt.png"];
[self addChild:spriteSheetmedAnt z:0 tag:kSpriteManager];

CCSprite *ant= [CCSprite spriteWithSpriteFrameName:@"small-aunt1.png"];
[spriteSheetmedAnt addChild:ant z:1 tag:currentAntTag];

NSMutableArray *walkAnimFrames = [NSMutableArray array];
for(int i = 1; i <= 2; ++i) {
    [walkAnimFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"small-ant%d.png", i]]];
}

CCAnimation *walkAnim = [CCAnimation animationWithFrames:walkAnimFrames delay:0.15f];
CCAction *action=[CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:walkAnim restoreOriginalFrame:NO]];


ant.position = ccp(100,500);
[ant runAction:action];

CGPoint realDest = ccp(60,140);

int minDuration = 2.0;
int maxDuration = 5.0;
int rangeDuration = maxDuration - minDuration;
int actualDuration = (arc4random() % rangeDuration) + minDuration;

[ant runAction:[CCSequence actions:
                       [CCMoveTo actionWithDuration:actualDuration position:realDest],
                       [CCCallFuncN actionWithTarget:self selector:@selector(moveFinished:)],
                       nil]];

}

-(void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event  
{
CGPoint touchLocation = [self convertTouchToNodeSpace:touch];

CCSpriteBatchNode *spriteManager;
spriteManager = (CCSpriteBatchNode*)[self getChildByTag:kSpriteManager];
CCSprite *ant = (CCSprite*)[spriteManager getChildByTag:currentAntTag];

CGRect abc= CGRectInset([ant boundingBox],30, 85);

if(CGRectContainsPoint(abc,touchLocation))  
{

    ant.visible=NO;
}
}

also i have 3 methods which are called every few seconds in which i create these CCSpriteFrameCache and CCSpriteBatchNode object to make my character run while it animates. will it be too heavey to crate caches every second like this or should i create them in init method and just run the action on CCSprite here??


Solution

  • Subclass CCSprite. Then in it's init:

    [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:NO];
    

    Implement the ccTouch methods:

    - (BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event;
    - (void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event;
    - (void) ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event;
    - (void) ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;
    

    Now you have two options. You can have a delegate variable to callback or use NSNotifications. Go with the callback here, it's faster.

    // in your @interface
    id touchDelegate; // between the {}'s
    
    @property (nonatomic, assign) id touchDelegate;
    

    Inside your game class, when you're creating your bad guys:

    NewCCSprite = newSprite = [NewCCSprite init];
    newSprite.touchDelegate = self;
    

    And when you touch one:

    - (void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
        if (self.touchDelegate == nil) return;
        [self.touchDelegate performSelector:@selector(touched:) withDelay:0.0f];
    }
    

    Finally, your touch: method:

    - (void) touch:(id)sender {
        NewCCSprite* sprite = (NewCCSprite*)sender;
        // hide/kill off/etc
    }