首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Unity Vector2.在一定时间内向下移动

Unity Vector2.在一定时间内向下移动
EN

Stack Overflow用户
提问于 2019-02-17 01:04:45
回答 1查看 181关注 0票数 0

我在为我的鼻咽癌设置AI时遇到了麻烦。我想让它在我地图上的随机点周围走动,当玩家靠近时,它就会跑开。当我追逐我的npc时,转义的虫子很好,但是当我停下来的时候,它们会向玩家的方向和向后弹,而不是仅仅设置另一个目的地…

这是代码。我将runToRandomLocation()放在Update()方法中。

代码语言:javascript
复制
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
        }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2019-02-17 02:27:05

仅当到达以前的目的地时,才会生成新的随机目的地。这里似乎发生的事情是,在NPS逃得足够远之后,它将继续移动到它在逃跑之前拥有的最后一个随机目的地,因此它将返回。可能是在玩家的方向上。因此,在一帧之后,它再次靠近玩家,并再次跑开。然后在循环中再次返回到旧的目的地,依此类推。你需要做的只是在运行完away.For后重新生成随机目的地,你需要一些状态机,就像@退休忍者指出的那样,但它实际上是一个非常原始的状态机。例如,下面这样的代码应该是有效的:

代码语言:javascript
复制
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
        }
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54725542

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档