【问题标题】:NavMeshAgent stopping before reaching it's destination Unity3DNavMeshAgent 在到达目的地 Unity3D 之前停止
【发布时间】:2021-02-06 02:20:44
【问题描述】:

我正在使用 c# 在 Unity 中创建一个 3D FPS 游戏。我有一个敌方 AI 使用 NavMeshAgent 巡逻一个区域。我有一种方法可以在地图上选择一个随机位置,然后告诉敌人去那个点,一旦它到达那个点,它应该在地图上选择另一个随机点,但是它只在某些时候有效.有时它会在该点附近停止,但即使没有任何东西告诉它停止,它也不会在该点停止,并且它不会选择新的点。有谁知道这个问题的解决方案吗?

这是我的脚本:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using Random = UnityEngine.Random;

public class EnemyController : MonoBehaviour
{
    public NavMeshAgent agent;
    public LayerMask groundMask;
    
    //Patrolling Area
    public Vector3 walkPoint;
    private bool walkPointSet;
    public float walkPointRange;
    
    
    // Start is called before the first frame update
    void Start()
    {
        agent = GetComponent<NavMeshAgent>();
    }

    // Update is called once per frame
    void Update()
    {
            Patrol();
    }

    void Patrol()
    {
        if (!walkPointSet)
        {
            SearchWalkPoint();
        }

        Vector3 distanceToWalkPoint = transform.position - walkPoint;
        
         //when walk point is reached
         if (distanceToWalkPoint.magnitude < 1f)
         {
             walkPointSet = false;
         }
    }

    void SearchWalkPoint()
    {
        //calculate random point in range
        float randomZ = Random.Range(-walkPointRange, walkPointRange);
        float randomX = Random.Range(-walkPointRange, walkPointRange);
        
        walkPoint = new Vector3(transform.position.x + randomX, transform.position.y, transform.position.z + randomZ);

        //checks if random walk point is inside of the map
        if (Physics.Raycast(walkPoint, -transform.up, 3f, groundMask))
        {
            walkPointSet = true;
        }
        
        agent.SetDestination(walkPoint);
    }

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    解决方案:我将变量 randomX 和 randomZ 添加到对象的当前 x 和 z 位置,这会创建某种偏移,从而影响某些随机值无法达到。解决方案只是将 randomX 和 randomZ 插入它们各自的点,而不是将数字添加到当前位置。更新后的代码如下:

    walkPoint = new Vector3(randomX, transform.position.y, randomZ);
    

    【讨论】:

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