有延迟地在阵列中移动几个SKSpriteNode?

时间:2015-02-06 10:27:47

标签: ios objective-c sprite-kit skspritenode skaction

我在移动数组中的多个节点时遇到问题。有一个代码:

SKSpriteNode* paddle = (SKSpriteNode*)[self childNodeWithName: paddleXCategoryName];

SKAction *move = [SKAction moveTo:CGPointMake(paddle.position.x, CGRectGetMaxY(self.scene.frame)) duration:1.5];

NSMutableArray *shots = [[NSMutableArray alloc] init];

for (int i = 1; i<=10; i++) {
    SKSpriteNode *shot = [[SKSpriteNode alloc] initWithImageNamed:@"shoot.png"];
    shot.size = CGSizeMake(2, 5);

    shot.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(2, 6)];
    shot.physicsBody.categoryBitMask    = shotCategory;
    shot.physicsBody.contactTestBitMask = blockCategory;
    shot.physicsBody.collisionBitMask   = blockCategory;

    [shots addObject:shot];
}

int i = 0;
for (SKSpriteNode *shot in shots) {
    SKAction *wait = [SKAction waitForDuration:0.2+0.3*i];
    shot.position = paddle.position;
    [self addChild:shot];
    [shot runAction:[SKAction sequence:@[wait, move]] completion:^{
        [shot removeFromParent];
    }];
}

我只有一个节点在移动。我做错了什么?

2 个答案:

答案 0 :(得分:0)

他们都运行相同的移动动作。每个精灵都需要运行自己的动作副本。尝试使用move替换[move copy]来更改runAction语句:

[shot runAction:[SKAction sequence:@[wait, [move copy]]] completion:^{
    [shot removeFromParent];
}];

答案 1 :(得分:0)

实际上,所有节点都在一起移动到同一点。这是因为您没有在循环内增加i变量。请尝试下面的代码。为了使SKAction正常工作,还要将affectedByGravity设置为false。

int i = 0;
for (SKSpriteNode *shot in shots) {
    SKAction *wait = [SKAction waitForDuration:0.2+0.3*i];
    shot.position = paddle.position;
    [self addChild:shot];
    shot.physicsBody.affectedByGravity = false; // Added line.
    [shot runAction:[SKAction sequence:@[wait, move]] completion:^{
        [shot removeFromParent];
    }];

    i++; // Added line.
}