這可能不是最有效的答案,但它確實顯示瞭如何做到這一點。請記住,通常使用Sprite Kit,你最終會得到很多節點,因此將它們歸爲父類SKNode
是一個好主意,它也允許在樹中指定一個點,以便您可以輕鬆地將它放在下面。 NSLog
聲明只是用於測試/調試,我留下了,因爲他們可能會幫助你,如果你嘗試的代碼。
- (void)addOrbs {
SKNode *orbRoot = [SKNode node];
[orbRoot setName:@"ORB_ROOT"];
[self addChild:orbRoot];
for(int counter = 0; counter<5; counter++) {
SKSpriteNode *newOrb = [SKSpriteNode spriteNodeWithColor:[SKColor redColor] size:CGSizeMake(20, 20)];
[newOrb setPosition:CGPointMake(100, 100 + (100*counter))];
NSLog(@"ORB POS: %@", NSStringFromCGPoint([newOrb position]));
[newOrb setName:@"orbSprite"];
[orbRoot addChild:newOrb];
}
}
。
- (void)removeOrbAtPoint:(CGPoint)point {
SKNode *orbRoot = [self childNodeWithName:@"//ORB_ROOT"];
NSArray *allOrbs = [orbRoot children];
NSLog(@"ORBS: %@", allOrbs);
for(SKNode *eachOrb in allOrbs) {
if([eachOrb position].x == 100 && [eachOrb position].y == 200) {
NSLog(@"REMOVING: %@ WITH POSITION: %@", [eachOrb name], NSStringFromCGPoint([eachOrb position]));
[eachOrb removeFromParent];
}
}
}
使用快速塊枚舉刪除的另一種版本:
- (void)removeOrbAtPoint_v2:(CGPoint)point {
SKNode *orbRoot = [self childNodeWithName:@"//ORB_ROOT"];
NSArray *allOrbs = [orbRoot children];
NSLog(@"ORBS: %@", allOrbs);
[orbRoot enumerateChildNodesWithName:@"orbSprite" usingBlock:^(SKNode *node, BOOL *stop) {
if([node position].x == 100 && [node position].y == 200) {
NSLog(@"REMOVING: %@ WITH POSITION: %@", [node name], NSStringFromCGPoint([node position]));
[node removeFromParent];
}
}];
}