【问题标题】:removefromparent in SpriteKit causes other nodes to "lose" propertiesSpriteKit 中的 removefromparent 导致其他节点“丢失”属性
【发布时间】:2014-06-10 19:51:40
【问题描述】:

我正在使用 SpriteKit 开发游戏。

我的主要精灵节点是这样定义的:

  ball = [SKSpriteNode spriteNodeWithImageNamed:@"green"];
  ball.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:ball.frame.size];
  ballcoordinates = CGPointMake(x, y);
  ball.position = ballcoordinates;
  ball.name = @"green";
  [self addChild:ball];

我还有其他带有 .name 字符串“蓝色、红色、黄色...”的球精灵。它们被多次添加并排列在二维网格中。

基本上我的代码所做的是:

  1. 使用 touchesBegan 选择一个球 Sprite:

    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    touchedNode = (SKSpriteNode *)[self nodeAtPoint:[touch locationInNode:self]];
    }
    
  2. 使用 nodeAtPoint 从周围(上、下、左、右)节点的坐标中选择周围节点。所以右边的节点看起来像:

    CGPoint right= CGPointMake(touchedNode.position.x + 63, touchedNode.position.y);
    SKNode *rightNode = [ball.parent nodeAtPoint:right];
    
  3. 如果触摸的字符串名称等于任何周围节点的字符串名称,则所有具有相同名称的节点都是 A.)添加到数组 B.)检查所有周围节点后删除

    NSMutableArray* ballArray;
    [ballArray addObject:rightNode];
    //Repeated for up,down,left
    
    for (id ball in ballArray) {
    [ball removeFromParent];
    }
    

它在 75% 的时间里都能完美运行。剩下的 25%,它一直工作到从父节点中删除节点为止。之后,如果我点击网格的另一个区域,我的 .name 字符串将为点击的节点返回正确的名称,但为周围的节点返回 null。所以要么我从 nodeAtPoint 选择节点的方式是错误的,要么 removeFromParent 正在删除一个属性。

我在这方面花了很多时间,但仍然很困惑。有什么建议么?

【问题讨论】:

    标签: objective-c ios7 sprite-kit


    【解决方案1】:

    您是否考虑过在 removeFromParent 之后节点消失(解除分配)? ballArray 本身不会保留,直到 3. 中的方法结束,特别是它不会保留任何开始的节点,因为假设上面的代码片段是你所拥有的,ballArray 只是 nil - 你没有分配一个实例NSMutableArray.

    改成:

    NSMutableArray* ballArray = [NSMutableArray array];
    

    并且可能也将声明移动到@interface,以便数组成为 ivar 而不是在方法结束时释放的本地 var。

    【讨论】:

    • 对不起,我应该澄清一下。我之前确实分配过。我会编辑我的问题。我知道它被释放了,但是如果我想删除数组中的所有节点,这不重要吗?我添加的所有节点都应该被删除。这不应该影响未添加的节点。
    • 还尝试了一种不同的方法,在该方法中,我为要删除的每个节点重新分配了一个名称,即“标记”。然后我使用 enumerateChildNodesWithName@"marked" 并从父级中删除。再次,它工作了〜3/4次。这很令人困惑,因为touchedNode = (SKSpriteNode *)[self nodeAtPoint:[touch locationInNode:self]];删除后仍然显示正确的名称。
    猜你喜欢
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多