统一navimesh和我建立的ai代码的问题

时间:2019-05-19 03:18:39

标签: c# unity3d artificial-intelligence

首先,对不起,有时我的英语会有点难以理解,我会尽力而为。

实际上,我正在尝试使用统一的Navimesh Component构建一个简单的AI系统,我的目标是:

  • NPC会检查女巫玩家离它的位置最近,然后去那里杀死他。
  • 如果目标玩家面对我逃跑

我的实际代码正在运行,但存在一些问题

 private Transform player;
 private UnityEngine.AI.NavMeshAgent myNMagent;
 private Transform startTransform;

 public float multiplyBy;
 public Vector3 resultedVector;


 // Use this for initialization
 void Start () {

     player = GameObject.FindGameObjectWithTag ("Player").transform;
     myNMagent = this.GetComponent<UnityEngine.AI.NavMeshAgent> ();

     RunFrom ();
 }

 // Update is called once per frame
 void Update () {


     //if is not facing got to eat him
    if(!ISFacing())
    {
        GotToEat();      
    }
    else
    {
        RunFrom ();
    }
 }

 public void RunFrom()
 {


     startTransform = transform;

     transform.rotation = Quaternion.LookRotation(transform.position - player.position);

     Vector3 runTo = transform.position + transform.forward * multiplyBy;

     NavMeshHit hit;    



    if(NavMesh.SamplePosition(runTo, out hit, 50, 1 << NavMesh.GetAreaFromName("Walkable")))
    {
        transform.position = startTransform.position;
        transform.rotation = startTransform.rotation;

        myNMagent.SetDestination(hit.position);
    }
    else
    {
        Debug.Log("not hitting");
    }


 }

 private void GotToEat()
 {
     transform.rotation = Quaternion.LookRotation(player.position - transform.position);
     myNMagent.SetDestination(player.transform.position);
 }
 private bool ISFacing()
 {
    float angle = 45;
    float angleToPlayer = Vector3.Angle(player.transform.forward.normalized,( transform.position - player.transform.position).normalized);

     if( angleToPlayer < angle)
     {
         return true;
     }
     else
     return false;
 }
bool IsHit(out Vector3 result)
{
    for (int i = 0; i < 30; i++)
    {
        Vector3 fixedPoint = transform.position + transform.forward * multiplyBy;
        NavMeshHit hit;
        if (NavMesh.SamplePosition(fixedPoint, out hit, 10.0f,1 << NavMesh.GetAreaFromName("Walkable")))
        {
            result = hit.position;
            return true;
        }
    }
    result = Vector3.zero;
    return false;
}

当NPC到达我的地图角落时,它将不再移动将冻结在那里。

我想我应该检查击中的navmesh是否“可行走”,但是我的函数将始终返回true,因此我无法告诉navimesh朝任何其他方向前进。.

我想念什么?

其中的视频

video

0 个答案:

没有答案