简体   繁体   中英

access child nodes in spritekit

Hi all i'm new in spriteKit and objective-c and I would like to create a spriteNode in a method and remove it in another method (same .m file) In this method i create the 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 touching it, but I only know the method for handle touch events is:

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

I'm trying to access my spaceship node from there i can't. I've tried everything without success. IS there a way to send a node from a method to another?? Or without sending it, is it posible to access to a children node from a method where it's not declared??

Try this:

-(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 set name of your node:

[sprite setName:@"NodeName"];

And you can access it by name:

[self childNodeWithName:@"NodeName"];

Yes, there is a way.

Every SKNode object has a property (of class NSString) called "name". And you can use this name to enumerate children of a node.

Try this:

spaceship.name = @"spaceship";

and in touchesBegan

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

be careful though, this will remove every node with the name "spaceship" from it's parent. If you want to be more selective about the removal process, you can either subclass SKSpriteNode to hold some values that you can use to figure out if it should be removed or not, or you can add your sprites into arrays based on some logic and then remove using the array.

Good luck!

Using the "name" property works, but if you think you'll only have one instance of that node you should create a property.

@property (strong, nonatomic) SKSpriteNode *spaceship;

Then when you want to add it:

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

 [self addChild:self.spaceship];

Then in 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];
    }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM