![](/img/trans.png)
[英]Confusion about coordinates, frames & child nodes in SpriteKit on iOS?
[英]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
我正试图从那里访问我的宇宙飞船节点我不能。 我尝试了一切都没有成功。 有没有办法将节点从一个方法发送到另一个? 或者不发送它,是否可以从未声明的方法访问子节点?
尝试这个:
-(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"];
是的,有一种方法。
每个SKNode对象都有一个名为“name”的属性(类NSString)。 您可以使用此名称枚举节点的子节点。
尝试这个:
spaceship.name = @"spaceship";
并在touchesBegan
[self enumerateChildNodesWithName:@"spaceship" usingBlock:^(SKNode *node, BOOL *stop) {
[node removeFromParent];
}];
但请注意,这将从其父级删除名为“spaceship”的每个节点。 如果你想对删除过程更有选择性,你可以将SKSpriteNode子类化为保存一些可用于确定是否应该删除它们的值,或者你可以根据某些逻辑将精灵添加到数组中然后使用数组删除。
祝好运!
使用“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];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.