简体   繁体   中英

Touching nodes is sprite kit

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?

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.
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM