删除SpriteKit中的特定节点

时间:2014-12-21 11:24:59

标签: ios sprite-kit sklabelnode

作为初学者需要一些帮助:我有不同的节点:4个方块(sprite1)和1个计数器(counterLabel,计算已删除的节点)。我想通过触摸来移除4个方块。使用下面的代码可以删除正方形,也可以删除计数器。奇怪的是,因为我试图专门解决方形节点(sprite1)。有没有可能只删除方形节点(精灵1)?

@implementation GameScene {
    BOOL updateLabel;
    SKLabelNode *counterLabel;
}

int x;
int y;
int counter;

-(id)initWithSize:(CGSize)size {    
    if (self = [super initWithSize:size]){

    self.backgroundColor = [SKColor /*colorWithRed:0.15 green:0.15 blue:0.3 alpha:1.0*/ whiteColor];

    counter = 0;

    updateLabel = false;

    counterLabel = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
    counterLabel.name = @"myCounterLabel";
    counterLabel.text = @"0";
    counterLabel.fontSize = 48;
    counterLabel.fontColor = [SKColor greenColor];
    //counterLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentModeCenter;
    //counterLabel.verticalAlignmentMode = SKLabelVerticalAlignmentModeBottom;
    counterLabel.position = CGPointMake(50,50); // change x,y to location you want
    //counterLabel.zPosition = 900;
    [self addChild: counterLabel];
    }
    return self;
}


-(void) didMoveToView:(SKView *)view {

    SKTexture *texture1 = [SKTexture textureWithImageNamed:@"square"];

    for (int i = 0; i < 4; i++) {
    x = arc4random()%668;
    y = arc4random()%924;
    SKSpriteNode *sprite1 = [SKSpriteNode spriteNodeWithTexture:texture1];
    sprite1.position = CGPointMake(x, y);
    sprite1.name = @"square";

    [self addChild:sprite1];
    }
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];

    NSArray *nodes = [self nodesAtPoint: [touch locationInNode: self]];

    for (SKNode *sprite1 in nodes) {

    [sprite1 removeFromParent];

    counter ++;
    updateLabel = true;
    }
}

-(void)update:(CFTimeInterval)currentTime {

    if(updateLabel == true){
    counterLabel.text = [NSString stringWithFormat:@"%i",counter];
    updateLabel = false;
    }
}

@end

1 个答案:

答案 0 :(得分:1)

您应该使用SKSpriteNode的属性name

在这种情况下你可以这样做:

for (SKNode *sprite1 in nodes) {

   if(![sprite1.name isEqualToString:@"myCounterLabel"]) {

    [sprite1 removeFromParent];

   }

    counter ++;
    updateLabel = true;
}

因此,如果SKNode名称与counterLabel的名称不同,则removeFromParent。

相关问题