Unity navmesh。跟随+停止距目标一定距离

时间:2017-05-25 18:09:48

标签: unity3d navmesh

嗨,所以我试图创造的是玩家可以右键点击一个敌人,他会跟随一定距离。这工作正常。但我想要做的也是停在那个距离。目前,如果敌人停下来,他将尝试前往其确切的位置,而不是停止一点点,这就是我目前所拥有的。

     using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 using UnityEngine.AI;
 public class Attacking : MonoBehaviour {
     NavMeshAgent agent;
     Transform target;
     public float distance;
     public float followDistance;
     // Use this for initialization
     void Start () {
         agent = GetComponent<NavMeshAgent>();
     }

     // Update is called once per frame
     void Update () {
         if (Input.GetMouseButton(0))
         {
             target = null;
         }
             if (Input.GetMouseButton(1))
         {
             RaycastHit hit;

             if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100))
             {
                 if (hit.collider.gameObject.tag == "enemy" || hit.collider.gameObject.tag == "Player")
                 {
                     target = hit.collider.transform;
                 }

             }
         }
         if(target != null)
         {
             distance = Vector3.Distance(transform.position, target.position);
             if (followDistance <= distance)
                 agent.destination = target.position;
         }
     }
 }

1 个答案:

答案 0 :(得分:1)

将一个脚本附加到你的敌人并给它一个半径,比如3f。

public float radius=3f;

为了更好地理解和使用视觉辅助OnDrawGizmosSelected()(在您的敌人脚本上)。

void OnDrawGizmosSelected ()
{
Gizmos.color=Color.yellow;
Gizmos.DrawWireSphere(transform.position,radius);

}

现在,在您的播放器脚本上使用agent.StoppingDistance()

if(target != null)
     {
         distance = Vector3.Distance(transform.position, target.position);
         if (followDistance <= distance){
             agent.destination = target.position;
             agent.StoppingDistance=target.radius;
            }


     }

注意:您必须将目标从转换更改为播放器的实例