Reputation: 2221
I am trying to make a game in cocos2d wherein I have sprites dropping from the top of the screen. Now, once the sprite is tapped, it should move back up. This works for me just fine but, there are some instances wherein the sprite would go back down after it goes off the screen. Also, my sprites don't disappear once they reach a certain y-axis position on the screen. Here's part of my code
-(void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint loc = [[CCDirector sharedDirector]convertToGL:[touch locationInView:[touch view]]];
CGRect rect = CGRectMake(sprite.position.x - (sprite.contentSize.width/2), sprite.position.y - (sprite.contentSize.height/2), sprite.contentSize.width, sprite.contentSize.height);
if(CGRectContainsPoint(rect, loc))
{
[sprite runAction:[CCCallFuncN actionWithTarget:self selector:@selector(spriteCaught)]];
}}
-(void)spriteCaught
{
//currentPos is an integer to get the current position of the sprite
id moveUp = [CCMoveTo actionWithDuration:1 position:ccp(currentPos, 500)];
[sprite runAction:[CCSequence actions:moveUp, nil]];
if(sprite.position.y >= 480)
{
[self removeChild:sprite cleanup:YES];
}}
Also, I'm not sure if my syntax is correct but my conditional statement (The one that checks the position in the y-axis of the sprite) doesn't work either. How do I go about fixing this? Any help and suggestion is greatly appreciated
Upvotes: 1
Views: 618
Reputation: 22042
Instead of manual rect, use sprite's bounding box.
if(CGRectContainsPoint([sprite boundingBox], loc))
Also update spriteCaught function.
-(void)spriteCaught
{
CGSize s = [[CCDirector sharedDirector] winSize];
float dest_y = s.height+sprite.contentSize.height*0.5f; //assumed ur sprite's anchor y = 0.5
//currentPos is an integer to get the current position of the sprite
id moveUp = [CCMoveTo actionWithDuration:1 position:ccp(sprite.position, dest_y)];
id calBlokc = [CCCallBlockN actionWithBlock:^(CCNode *node)
{
//here node = sprite tht runs this action
[node removeFromParentAndCleanup:YES];
}];
id sequence = [CCSequence actions:moveUp, calBlokc, nil];
[sprite runAction:sequence];
}
Upvotes: 1