1

作为初学者需要一些帮助:我有不同的节点: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
4

1 回答 1

1

你应该使用nameSKSpriteNode的属性

在这种情况下,您可以这样做:

for (SKNode *sprite1 in nodes) {

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

    [sprite1 removeFromParent];

   }

    counter ++;
    updateLabel = true;
}

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

于 2014-12-21T11:31:31.530 回答