我一直在努力为我的Enemy课程创建AI,而且我在更新哪个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];
谢谢
答案 0 :(得分: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)
}
}