Access child nodes in spritekit

Hello everyone. I am new to spriteKit and objective-c, and I would like to create a spriteNode in a method and delete it in another method (same .m file) In this method, create a sprite:

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

        //code...

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

And now I would like to remove the node by touching it, but I only know that the method for touch control events is:

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

I am trying to access my spaceship node from there, I cannot. I tried everything without success. Is there a way to send a node from a method to another? Or, without sending it, it is a node accessible to children from a method in which it was not declared

+4
source share
3 answers

Try the following:

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

You can also specify the name of your node:

[sprite setName:@"NodeName"];

:

[self childNodeWithName:@"NodeName"];
+8

, .

SKNode ( NSString), "". node.

:

spaceship.name = @"spaceship";

touchesBegan

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

, node " " . , SKSpriteNode , , , , , .

!

+2

"name" , , node, .

@property (strong, nonatomic) SKSpriteNode *spaceship;

, :

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

 [self addChild:self.spaceship];

Began:

-(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];
    }
} 
0

All Articles