【问题标题】:access child nodes in spritekit访问 spritekit 中的子节点
【发布时间】:2013-11-25 18:44:49
【问题描述】:

大家好,我是 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

我正在尝试从那里访问我的飞船节点,但我无法访问。我已经尝试了一切都没有成功。有没有办法将节点从一个方法发送到另一个?还是不送,是吗 可以从未声明的方法访问子节点吗??

【问题讨论】:

    标签: ios objective-c sprite-kit


    【解决方案1】:

    试试这个:

    -(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" 中的< 是错字还是我不熟悉的语法?
    • @MartinThompson 我编辑了,错字了,谢谢指点。
    【解决方案2】:

    是的,有办法。

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

    试试这个:

    spaceship.name = @"spaceship";
    

    touchesBegan

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

    不过要小心,这会从其父节点中删除每个名为“spaceship”的节点。如果你想对删除过程更有选择性,你可以继承 SKSpriteNode 来保存一些值,你可以用这些值来确定它是否应该被删除,或者你可以根据一些逻辑将你的精灵添加到数组中,然后使用数组删除。

    祝你好运!

    【讨论】:

      【解决方案3】:

      使用“名称”属性是可行的,但如果您认为只有该节点的一个实例,您应该创建一个属性。

      @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];
          }
      } 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-07
        • 1970-01-01
        • 2014-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-13
        相关资源
        最近更新 更多