ios - 删除 SpriteKit 中的特定节点

标签 ios sprite-kit sklabelnode

作为初学者需要一些帮助:我有不同的节点:4 个正方形 (sprite1) 和 1 个计数器(counterLabel,计算节点数,已被删除)。我想通过触摸来移除 4 个正方形。使用下面的代码可以删除方 block ,也可以删除计数器。奇怪的是,因为我试图专门处理方形节点 (sprite1)。是否有可能专门删除方形节点( Sprite 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

最佳答案

你应该使用 SKSpriteNode 的属性 name

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

for (SKNode *sprite1 in nodes) {

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

    [sprite1 removeFromParent];

   }

    counter ++;
    updateLabel = true;
}

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

关于ios - 删除 SpriteKit 中的特定节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27588892/

相关文章:

Swift 4 SKLabelNode 没有出现

sprite-kit - 没有透明背景的SKLabelNode

swift - Sprite Kit 按钮触摸位置错误 | swift

ios - iOS 开发者企业计划上受用户名/密码保护的应用程序

swift - 如何将不同高度的 Sprite 锚定到相同的 Y 位置

ios - 如何快速添加图像作为大型导航栏上的标题?

ios - Swift Jump Method 物体与地面碰撞

ios - 节点移动后SKSpriteNode的X、Y坐标不变

ios - SLComposeViewController setInitialText 未显示在 View 中

ios - 获取从照片库中选取的视频的缩略图