I am trying to make an app where bugs run across the screen and get squashed. I am having a problem though. I have code that makes it so when I touch a bug running across the screen, it disappears. Though, this only works on the right side. This is my code to get rid of the bug.
-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch * touch = [touches anyObject];
CGPoint touchLocation = [touch locationInView:[touch view]];
touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation];
touchLocation = [self convertToNodeSpace: touchLocation];
if (CGRectContainsPoint(bug.boundingBox, touchLocation)) {
[self removeChild:bug cleanup:YES];
}
}
Then, this is my code to spawn the bug on the right side of the screen
- (void) addBug {
bug = [CCSprite spriteWithFile:@"bug.jpg"];
CGSize size = [[CCDirector sharedDirector] winSize];
int minY = bug.contentSize.height /2;
int maxY = size.height - bug.contentSize.height /2;
int rangeY = maxY - minY;
int actualY = (arc4random() % rangeY) + minY;
bug.position = ccp(size.width + bug.contentSize.width/2, actualY);
[self addChild:bug];
int minSpeed = 2.0;
int maxSpeed = 4.0;
int rangeSpeed = maxSpeed - minSpeed;
int actualDuration = (arc4random() % rangeSpeed) + minSpeed;
actionMove = [CCMoveTo actionWithDuration:actualDuration
position:ccp(-bug.contentSize.width/2, actualY)];
actionMoveDone = [CCCallBlockN actionWithBlock:^(CCNode *node) {
[node removeFromParentAndCleanup:YES];
}];
[bug runAction:[CCSequence actions:actionMove, actionMoveDone, nil]];
}
-(void)gameLogic:(ccTime)dt {
[self addBug];
}
In the init, I have
[self setTouchEnabled:YES];
[self schedule:@selector(gameLogic:) interval:1.0];
I also have a background, if that matters. I've also tested with logs if the bugs are being touched but not removed on the left side of the screen, when I click the bugs in the simulator, nothing is logged, though when I click them on the right side of the screen, it is logged successfully. Thank you very much for helping.
*Edit, I adjusted the interval for gameLogic:, the left side works when there is only one bug on the screen at once. How should I adjust my code to make this work so there can be multiple bugs on the screen at once and I can still remove them all? I am guessing, the code I am using, creates a bounding box for the most current bug and removes all the other bounding boxes. Any additional help would be great! Thank you!
You're adding bugs on each gameLogic:
invocation, but you only keep the pointer to the last created which leads to a collision check for a single one in ccTouchesBegan:withEvent:
. Add each new to an array or whatever data structure that suits your other needs and check against all objects in it.