Unity3D briefly in the wayfinding Navmesh

Often need to use pathfinding in the game, Asset Store there are many related plug-ins. Introduction U3D comes Navmesh here.

1. Terrain

First create a new local Plane table.

Then placed at random some geometric objects as obstacles on the Plane (note reserved roles by allowing path of) these obstacles and to add rigidbody.

 (The sub-Plane onto the obstacle objects) hit the surface with obstacles these groups to facilitate subsequent operation.

Plane Select group, open Navigation window, check the Static Navigation, suggesting while setting sub-object, determining point.

 

Click Bake in the Navigation panel, you are prompted to save the scene, determined and saved.

FIG After baking (namely the path through the blue part):

If baking out of the path is unreasonable, you can adjust the obstacles before baking.

 The tag Plane and its sub-objects to Terrain.

2. Role

When adding a Capsule role. Also add to it rigidbody components.

New Script CharacterController:

 1 public class PlayerController : MonoBehaviour
 2 {
 3 
 4     private NavMeshAgent agent;
 5 
 6     // Use this for initialization
 7     void Start ()
 8     {
 9         agent = GetComponent<NavMeshAgent>();
10     }
11     
12     // Update is called once per frame
13     void Update () {
14 
15         //鼠标点击场景设置目标点
16         if (Input.GetMouseButtonDown(0))
17         {
18             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
19             RaycastHit hit;
20             //如果点击目标点为地形
21             if (Physics.Raycast(ray,out hit))
22             {
23                 if (!hit.collider.tag.Equals("Terrain"))
24                 {
25                     return;
26                 }
27 
28                 Vector3 point = hit.point;
29                 //角色转向
30                 transform.LookAt(new Vector3(point.x,transform.position.y,point.z));
31                 //设置目标点
32                 agent.SetDestination(point);
33             }
34         }
35 
36         //正在行走,则输出提示
37         if (agent.remainingDistance > 0)
38         {
39             Debug.Log("seeking");
40         }
41     }
42 }
View Code

 

运行场景,点击目标点,看看是不是寻路成功。

转载于:https://www.cnblogs.com/seancheung/p/4028231.html

Guess you like

Origin blog.csdn.net/weixin_33810302/article/details/93296782