1

我一直在尝试为我的 Enemy 类创建 AI,但在更新最接近 Player 的 Enemy 时遇到问题。它在只有两个敌人但有 3 个或更多敌人时才有效。我只想要最近的攻击,但除​​了最远的敌人之外的所有敌人。我认为这是因为三个或更多的精灵可以在其他精灵之间使他的位置安全位置和攻击位置,但是当任何临时敌人在他们面前时,我如何让中间的敌人意识到呢?

 CCArray *fellowEnemy = [self allyArray];
for (int i = 0; i<[fellowEnemy count]; i++) {
    Enemy *tempEnemy = [fellowEnemy objectAtIndex:i];
    if (tempEnemy == self) continue;
    CGPoint tempDifference = ccpSub(player.position, tempEnemy.position);
    CGPoint selfDifference = ccpSub(player.position, self.position);
    float tempToPlayer = ccpLength(tempDifference);
    float selfToPlayer = ccpLength(selfDifference);

    if (tempToPlayer > selfToPlayer) {
        newPosition = attackPosition;

    }else if (tempToPlayer < selfToPlayer){
        newPosition = safePosition;

    }else{
        newPosition = safePosition;
    }
}

[self setPosition:newPosition];

谢谢你

4

1 回答 1

0

如果我正确理解了您的问题,那么您正在尝试确定离玩家最近的敌人。中间的那个永远是最接近玩家的。所以你只需要找出与玩家距离最小的那个。

    CCArray *fellowEnemy = [self allyArray];
    if( fellowEnemy.count > 0 )
    {
        Enemy *closestEnemy = nil;
        float minDistance = 0;

        for (int i = 0; i<[fellowEnemy count]; i++) {
            Enemy *tempEnemy = [fellowEnemy objectAtIndex:i];
            if (tempEnemy == self) continue;

            if( closestEnemy == nil )
            {
                closestEnemy = tempEnemy;
                minDistance = ccpDistance(player.position, closestEnemy.position);
                continue;
            }

            float curDistance = ccpDistance(player.position, tempEnemy.position);
            if( curDistance < minDistance )
            {
                minDistance = curDistance;
                closestEnemy = tempEnemy;
            }
        }

        if( closestEnemy != nil )
        {
            // Here you have closest enemy 
            // Write your remaining logic (position, attack... whatever)
        }
    }
于 2013-02-07T20:39:10.030 回答