【问题标题】:Unity Vector2.MoveTowards for certain amount of timeUnity Vector2.MoveTowards 一段时间
【发布时间】:2019-02-16 17:04:44
【问题描述】:

我在为我的 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
        }
    }
}

【问题讨论】:

  • 您确实需要一个状态机,但您设置随机目标(第一个 if)的代码实际上并没有对该目标执行任何操作。它不会移动任何东西。

标签: c# unity3d artificial-intelligence


【解决方案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
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多