在SpriteKit中访问子节点

4

大家好,我是一个新手,正在学习SpriteKit和Objective-C。我想创建一个精灵节点,并在另一个方法中将其删除(同一.m文件中)。 在这个方法中,我创建了精灵:

(void)createSceneContents{ /*in this method i create and add the spaceship spriteNode
        SKSpriteNode *spaceship = [SKSpriteNode spriteNodeWithImageNamed:@"Spaceship"];

        //code...

        //Add Node
        [self addChild:spaceship];
    }

现在我想删除与之接触的节点,但是我只知道处理触摸事件的方法是:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

我正在尝试从那里访问我的太空船节点,但无法成功。我已经尝试了一切都没有成功。有没有办法在一个方法中发送节点到另一个方法?或者在未声明它的方法中访问子节点是否可行?

3个回答

8

试试这个:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint positionInScene = [touch locationInNode:self];
    SKSpriteNode *touchedNode = (SKSpriteNode *)[self nodeAtPoint:positionInScene];
}

您还可以设置节点的名称:
[sprite setName:@"NodeName"];

您可以通过名称访问它:

[self childNodeWithName:@"NodeName"];

<@"NodeName" 中的 < 是一个错字还是一种我不熟悉的语法? - Martin Thompson
@MartinThompson 我已经编辑了,这是一个打字错误,感谢您指出。 - Greg

2

是的,有一种方法。

每个SKNode对象都有一个名为“name”的属性(NSString类),您可以使用此名称枚举节点的子项。

尝试这样做:

spaceship.name = @"spaceship";

touchesBegan中。
[self enumerateChildNodesWithName:@"spaceship" usingBlock:^(SKNode *node, BOOL *stop) {
    [node removeFromParent];
}];

要小心,这将从其父节点中删除所有名称为“spaceship”的节点。如果您想更有选择性地进行删除过程,可以通过子类化SKSpriteNode来保存一些值,以便确定是否应将其删除,或者可以根据某些逻辑将精灵添加到数组中,然后使用该数组进行删除。

祝你好运!


0

使用"name"属性是可以的,但如果您认为只会有一个该节点的实例,则应创建一个属性。

@property (strong, nonatomic) SKSpriteNode *spaceship;

然后当你想要添加它时:

 self.spaceship = [SKSpriteNode spriteNodeWithImageNamed:@"Spaceship"];

 [self addChild:self.spaceship];

然后在touchesBegan方法中:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = touches.anyObject;
    SKSpriteNode *node = [self nodeAtPoint:[touch locationInNode:self]];
    if (node == self.spaceship) {
        [self.spaceship removeFromParent];
    }
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接