SpriteKit - 如何添加具有特定距离的对象

时间:2014-02-11 09:04:34

标签: ios iphone objective-c xcode4 sprite-kit

在我的游戏中我每秒都会向场景中添加敌人,我需要描述我的主要角色穿过这些敌人的透视物体之间的特定距离,这里是我的代码,将敌人添加到场景中:

- (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 个答案:

答案 0 :(得分:1)

您可以创建新变量来保持前一个敌人的最后位置。

CGPoint positionOfLastEnemy;

当您创建新敌人时,将创建的敌人的位置分配给此变量:

positionOfLastEnemy = CGPointMake(xPostion, yPostion);

如果您需要更新敌人的位置,您可以在碰撞检测方法中执行此操作。

之后只需使用positionOfLastEnemy变量来计算你需要的距离。

另一种方法是添加变量来保持最后一个敌人

SKSpriteNode *lastEnemy;

在你的createEnemy方法中保存对你创建的敌人的引用。

lastEnemy = enemy;

如果您需要最后一个敌人的距离,请使用

lastEnemy.position