Reposition sprite nodes after SKAction is completed

I am trying to reposition my sprites after an SKAction moveTo action is completed. I have programmed the enemies to enter the screen from (self.frame.size.width/2, 0). They are moving only on the y axis. I want to reposition them on the initial position when their y position is bigger than (self.frame.size.height) and move them again and again in the same way until the player kills all of the enemies. I am struggling on this point.What part of code should I add? Any ideas? This code might help you understand my implementation :

-(void) addEnemies {

for (int j = 0; j < 6; j++) {

   SKSpriteNode* enemy = [SKSpriteNode spriteNodeWithImageNamed:@"player"];
    enemy.position = CGPointMake(((self.frame.size.width) -20) - j * (enemy.frame.size.width) , 0);


    CGPoint realDest = CGPointMake((enemy.position.x), (self.frame.size.height));
    float velocity = 50/1.0;
    float realMoveDuration = self.size.height / velocity;
    SKAction * actionMove = [SKAction moveTo:realDest duration:realMoveDuration];
    [enemy runAction:actionMove];

    [self addChild:enemy];
}

}

Upvotes: 1

Views: 95

Answers (2)

meisenman
meisenman

Reputation: 1828

  1. Create a SKSpriteNode that replicates a roof -> Rectangle(self.frame.size.width,1)
  2. Have it sit along the top edge of the screen with a non-dynamic physics body
  3. Set the "roof" and enemy to contact each other
  4. Call a method on contact that resets there position and calls the SKaction

This allows you to have direct access to each enemy exactly when it hits the top of the screen.

Here is an example of how to create a roof and have enemies interact with it. https://stackoverflow.com/a/24195006/2494064

Upvotes: 0

mihnea2kx
mihnea2kx

Reputation: 110

-(void)addEnemies{
    for (int j = 0; j < 6; j++) {

        SKSpriteNode* enemy = [SKSpriteNode spriteNodeWithImageNamed:@"player"];
        enemy.position = CGPointMake(((self.frame.size.width) -20) - j * (enemy.frame.size.width) , 0);

        [self addChild:enemy];
        [self moveEnemyNode:enemy];
    }
}
-(void)moveEnemyNode:(SKSpriteNode *)enemy{
    enemy.position = CGPointMake(enemy.position.x, 0);
    float velocity = 50/1.0;
    float realMoveDuration = self.size.height / velocity;
    SKAction *actionMove = [SKAction moveToY:self.frame.size.height + enemy.frame.size.height duration:realMoveDuration];
    [self runAction:actionMove completion:^{
        [self moveEnemyNode:enemy];
    }];
}

Upvotes: 1

Related Questions