1、第一种状况,不带自动寻路功能。ide
Vector3 targetPoint = Vector3.zero; //鼠标点击的位置 CharacterController controller; void Start () { targetPoint = transform.position; controller = GetComponent<CharacterController>(); } void Update () { if (Input.GetMouseButton (0)) { Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { //判断点击的是否地形 if (!hit.collider.name.Equals("Plane")) { return; } //点击位置坐标 targetPoint = hit.point; //转向 transform.LookAt(new Vector3(targetPoint.x, transform.position.y, targetPoint.z)); } } float distance = Vector3.Distance(targetPoint,transform.position);//计算目标位置到当前位置 if(distance > 0.3f) { controller.SimpleMove(transform.forward * 5f);//角色移动 } }2、第二种状况,加上自动寻路技术。
Vector3 targetPoint = Vector3.zero; //鼠标点击的位置 NavMeshAgent agent; bool flag = false; //控制到达目的地后输出一次提示 void Start () { targetPoint = transform.position; agent = GetComponent<NavMeshAgent>(); } void Update () { if (Input.GetMouseButton (0)) { flag = false; Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { //判断点击的是否地形 if (!hit.collider.name.Equals("Plane")) { return; } //点击位置坐标 targetPoint = hit.point; //转向 transform.LookAt(new Vector3(targetPoint.x, transform.position.y, targetPoint.z)); //设置寻路的目标点 agent.SetDestination(targetPoint); agent.speed = 4f; } } if (agent.remainingDistance == 0 && !flag) { flag = true; print ("到达了"); } }
3、记录一些遇到的问题。spa
一、使用第一种方式的时候,须要去掉组件“Nav Mesh Agent”,不然鼠标点击了可是物体不移动,缘由待查明。code
二、每为一个物体加上组件“Nav Mesh Agent”的时候,都须要从新对地形烘焙一次,不然会出现编译错误,“SetDestination can only be called on an active agent that has been placed on a navmesh”。orm