Question

in my game I am adding enemies to the scene every second , I need to describe an specific distance between pervious object that my main character move through these enemy , here is my codes that add enemy to the scene :

- (void)createEnemy {

       int GoOrNot = [self getRandomNumberBetween:0 to:1];

         if(GoOrNot == 1){

        int randomEnemy = [self getRandomNumberBetween:0 to:1];

        if(randomEnemy == 0)

        enemy =     [[SKSpriteNode alloc]initWithImageNamed:@"car.png"];

        else

        enemy =    [[SKSpriteNode alloc]initWithImageNamed:@"block.png"];


             int xPostion = [self placeRandomObject] ;
             int yPostion = 1150;

             enemy.position = CGPointMake(xPostion, yPostion);

             enemy.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:enemy.size];
             enemy.name = @"enemy";
             enemy.physicsBody.categoryBitMask = enemyCategory;
             enemy.physicsBody.contactTestBitMask = carCategory;
             enemy.physicsBody.collisionBitMask = 0;
             enemy.physicsBody.dynamic = YES;
             enemy.physicsBody.usesPreciseCollisionDetection = YES;

             [self addChild:enemy];



             SKAction *wait = [SKAction waitForDuration:.20];
             SKAction *move = [SKAction moveToY:self.scene.frame.origin.y-10 duration:enemySpeed];
             SKAction *remove = [SKAction removeFromParent];
             SKAction *runAction = [SKAction sequence:@[wait,move , remove]];
             [enemy runAction:[SKAction repeatActionForever:runAction]];
        }

}

adding enemy :

- (void)addEnemies {


    SKAction *wait = [SKAction waitForDuration:.55];
    SKAction *callEnemies = [SKAction runBlock:^{ [self createEnemy];}];

    updateEnimies = [SKAction sequence:@[wait,callEnemies]];

   [self runAction:[SKAction repeatActionForever:updateEnimies] withKey:@"addEnemy"];



}
Was it helpful?

Solution

You can create new variable to hold the last position of the previous enemy.

CGPoint positionOfLastEnemy;

when you create new enemy assign the position of created enemy to this variable:

positionOfLastEnemy = CGPointMake(xPostion, yPostion);

if you need to update the enemy position you can do it in your collision detection method.

After that just use the positionOfLastEnemy variable to calculate the distance you need.

The other way is to add variable to hold the last enemy

SKSpriteNode *lastEnemy;

in your createEnemy method save reference to your created enemy.

lastEnemy = enemy;

And if you need the distance of the last enemy just use

lastEnemy.position
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top