Unity射线&自动寻路/右键点击某一点会使物体跟随至鼠标点击位置/计算目标物体距离鼠标点击位置的距离

public class MyRay : MonoBehaviour {

public GameObject GameObject;//要实例化的物体 粒子特效

public GameObject Player;

// private Animation ani;

private NavMeshAgent Agent;
private float distance;

void Start ()
{
   Agent=   Player.GetComponent<NavMeshAgent>();
  //  ani = Player.GetComponent<Animation>();
}

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

    if (Input.GetMouseButtonDown(1))
    {
        //得到射线
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        //进行物理检测
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, 1000))
        {
            Debug.DrawLine(ray.origin, hit.point, Color.blue, 0.5f);
            //实例化特效 先定义特效物体
            Instantiate(GameObject, hit.point, Quaternion.identity);
            //改变材质颜色
       //     hit.collider.gameObject.GetComponent<Renderer>().material.color = Color.green;
            Agent.destination = hit.point;//把自动追踪的目标位置设置为碰撞点point

         //   ani.CrossFade("Battle_Run");
        }
    }
//计算距离

// distance = Agent.destination - Player.transform.position;
distance= Vector3.Distance(Agent.destination ,Player.transform.position);

猜你喜欢

转载自blog.csdn.net/qq_42987283/article/details/82666520