2014-02-11 62 views
0

我每秒都會向場景中添加敵人,我需要描述主角穿過這些敵人的透明物體之間的特定距離,這裏是我的代碼敵人的情景:SpriteKit - 如何在我的遊戲中添加具有特定距離的對象

- (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]]; 
     } 

} 

加入敵人:

- (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"]; 



} 

回答

1

您可以創建新的變量來保存先前的敵人的最後位置。

positionOfLastEnemy = CGPointMake(xPostion, yPostion); 

,如果你需要更新敵人的位置,你可以做你的碰撞檢測方法:

CGPoint positionOfLastEnemy; 
當你創建新的敵人分配創建敵人的位置,這個變量

之後,只需使用positionOfLastEnemy變量來計算你需要的距離。

的另一種方法是添加變量來保存最後的敵人

SKSpriteNode *lastEnemy; 
在createEnemy方法

保存引用您所創建的敵人。

lastEnemy = enemy; 

如果你需要最後的敵人的距離,只需要使用

lastEnemy.position 
+0

似乎它的工作!謝謝 –