Unity Vector2.MoveTowards在一定时间内

时间:2019-02-16 17:04:45

标签: c# unity3d artificial-intelligence

我在为NPC设置AI时遇到麻烦。我希望它绕过我地图上的随机点,并在玩家靠近时逃离玩家。当我追逐我的NPC时,逃避的担忧很好,但是当我停止追逐它们时,它们会朝着玩家向后弹跳,而不仅仅是设置另一个目标... 这是代码。我将runToRandomLocation()放在Update()方法中。

void runAway()
{
    if (!isDead)
    {
        transform.position = Vector2.MoveTowards(transform.position, player.transform.position, -movementSpeed * 1.5f * Time.deltaTime);            
    }
}

void runToRandomLocation()
{
    if (!isDead) {

        if (Vector2.Distance(transform.position, player.transform.position) > 3)    // if player is not near
        {
            if (Vector2.Distance(transform.position, randomDestination) <= 2)   // when NPC is close to destination he sets another
            {
                randomDestination = new Vector2(Random.Range(-11, 11), Random.Range(-5, 5));
            }
            else
            {
                transform.position = Vector2.MoveTowards(transform.position, randomDestination, movementSpeed * Time.deltaTime);   // NPC is just walking from point to point
            }
        }
        else
        {
            runAway();  // if player is near
        }
    }
}

1 个答案:

答案 0 :(得分:1)

仅当到达先前目的地时,才生成一个新的随机目的地。似乎正在发生的情况是,在NPS逃脱足够远之后,它将继续移动到逃跑之前的最后一个随机目的地,因此它将返回。可能是在玩家的方向上。因此,在一帧之后,它再次靠近播放器,并再次跑开。然后,再次循环返回旧目的地,依此类推。 您只需要在跑完后重新生成随机目的地即可,为此,您将需要一些状态机,正如@Retired Ninja指出的那样,但这实际上是一个非常原始的状态机。例如,类似这样的方法应该起作用:

private bool onTheRun = false;

void regenDestination() {
    randomDestination = new Vector2(Random.Range(-11, 11), Random.Range(-5, 5));
}

void runAway() {
    if (!isDead) {
        transform.position = Vector2.MoveTowards(transform.position, player.transform.position, -movementSpeed * 1.5f * Time.deltaTime);
        onTheRun = true;
    }
}

void runToRandomLocation() {
    if (!isDead) {

        if (Vector2.Distance(transform.position, player.transform.position) > 3)    // if player is not near
        {
            if (onTheRun)
            {
                regenDestination();
                onTheRun = false;
            }
            if (Vector2.Distance(transform.position, randomDestination) <= 2)   // when NPC is close to destination he sets another
            {
                regenDestination();
            } else {
                transform.position = Vector2.MoveTowards(transform.position, randomDestination, movementSpeed * Time.deltaTime);   // NPC is just walking from point to point
            }
        } else {
            runAway();  // if player is near
        }
    }
}