访问spritekit中的子节点(access child nodes in spritekit)

大家好我是spriteKit和objective-c的新手,我想在方法中创建一个spriteNode并在另一个方法中删除它(相同的.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

我试图从那里访问我的飞船节点,我不能。 我尝试了一切都没有成功。 有没有办法将一个节点从一个方法发送到另一个? 或者不发送它,是否可以从未声明的方法访问子节点?

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??

最满意答案

尝试这个:

-(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"];

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"];

更多推荐