将现有精灵添加为子精灵的最佳方法是什么?

时间:2013-10-07 22:07:23

标签: parent-child sprite-kit

我有以下内容:

  1. 一个名为“_background”的背景精灵
  2. 3个精灵“C4”,D5“和”Hj“
  3. 将三个精灵分别添加到背景上。然后,我再次点击一下,想要将它们全部同时拖动到屏幕上的另一个位置,同时它们保持相同的顺序和位置。

    我得到它的唯一方法是使用此代码:

    - (void)tap2TouchesGesture:(UITapGestureRecognizer *)sender {
    SKNode *removeNode = [_background childNodeWithName:@"C4"];
    CGPoint aPos = removeNode.position;
    [removeNode removeFromParent];
    
    
    SKSpriteNode *topNode = [SKSpriteNode spriteNodeWithImageNamed:@"C4"];
    topNode.position = aPos;
    topNode.zPosition = 100;
    topNode.name = @"C4";
    [_background addChild:topNode];
    
    removeNode = [_background childNodeWithName:@"D5"];
    [removeNode removeFromParent];
    
    
    SKSpriteNode *vv = [SKSpriteNode spriteNodeWithImageNamed:@"D5"];
    vv.position = CGPointMake(-10, -10);
    vv.zPosition = -10;
    vv.userInteractionEnabled = NO; // just testing
    vv.name = @"D5";
    [topNode addChild:vv];
    
    removeNode = [_background childNodeWithName:@"Hj"];
    [removeNode removeFromParent];
    vv = [SKSpriteNode spriteNodeWithImageNamed:@"Hj"];
    vv.position = CGPointMake(-20, -20);
    vv.zPosition = -50;
    vv.userInteractionEnabled = NO; // just testing
    vv.name = @"Hj";
    [topNode addChild:vv];
    }
    

    在处理完上面的代码后,我可以移动精灵包,但目前的问题是父亲C4似乎没有在顶部。选择C4的唯一方法是单击任何其他精灵之外的部分,不包括_background。

    我猜这不是执行此操作的最佳方法,所以我想请求一些如何正确执行此操作的帮助。另外,我可以通过点击整个精灵来选择C4。

2 个答案:

答案 0 :(得分:0)

你的意思是你希望能够同时和同步地拖动所有三个精灵,它们相对于彼此的位置总是保持不变?

在这种情况下,我总是说。如果你想要多个精灵(或任何节点)一起做某事,那么:添加一个SKNode,将所有三个精灵放入其中,拖动节点。 Bam,超级简单!

答案 1 :(得分:0)

我现在让它工作,我做了一个非常简单的错误,因为我试图移动所选节点而不是topNode(容器)。令人难以置信,我应该看到这一点,特别是在Steffens建议之后: - (

谢谢Steffen& Ben Stahl @ Apple SpriteKit论坛: - )

但是,以下是我用于此示例的代码:

- (void)tap2TouchesGesture:(UITapGestureRecognizer *)sender {

_topNode = [SKNode node];
[_background addChild:_topNode];


SKSpriteNode *vv = [SKSpriteNode spriteNodeWithImageNamed:@"C4"];
[_topNode addChild:vv];

vv = [SKSpriteNode spriteNodeWithImageNamed:@"D5"];
[_topNode addChild:vv];

vv = [SKSpriteNode spriteNodeWithImageNamed:@"Hj"];
[_topNode addChild:vv];

_isThePackSelectedForAction = YES; // sprites are selected

}


- (void)handlePan:(UIPanGestureRecognizer *)sender {

_currentTouchLocationGlobal = [sender locationInView:sender.view];
_currentTouchLocationGlobal = [self convertPointFromView:_currentTouchLocationGlobal];


if (_isThePackSelectedForAction) {
    _topNode.position = CGPointMake(_currentTouchLocationGlobal.x, _currentTouchLocationGlobal.y);
} else {
    _currentNode.position = CGPointMake(_currentTouchLocationGlobal.x, _currentTouchLocationGlobal.y);
}
}