Reputation: 190
I have a little Sprite Kit game where you have serval ants onscreen and when you touch them, they should disappear.
This is my code for adding an ant:
-(void)addAnt
{
SKSpriteNode *ant = [SKSpriteNode spriteNodeWithImageNamed:@"ant-icon"];
NSString *antName = [NSString stringWithFormat:@"ant %d",_antNumber];
_antNumber++;
ant.name = antName;
ant.xScale = 0.5;
ant.yScale = 0.5;
int lowestPositionX = ant.size.width/2;
int highestPositionX = self.size.width - ant.size.width/2;
int lowestPositionY = ant.size.height/2;
int highestPositionY = self.size.height - ant.size.height/2;
int randomSpiderXValue = lowestPositionX + arc4random() % (highestPositionX - lowestPositionX);
int randomSpiderYValue = lowestPositionY + arc4random() % (highestPositionY - lowestPositionY);
int randomRotaionValue = -2*M_PI + arc4random() % (int)(2*M_PI - 2*-M_PI);
ant.zRotation = randomRotaionValue;
ant.position = CGPointMake(randomSpiderXValue, randomSpiderYValue);;
[self addChild:ant];
}
Then, when the screen is touched, I would like to delete the ant that is touched. (ant %d). How can I iterate trough all the ants and just delete the touched one?
Upvotes: 1
Views: 249
Reputation: 40030
Iterate through the nodes at the touched point.
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
NSArray *nodes = [self nodesAtPoint:[touch locationInNode:self]];
for (SKNode *ant in nodes)
{
// Do something with touched ant.
}
}
Upvotes: 2