Unity 使用Navgation自动寻路绘制导航路线
一、烘焙平面路径
将所在平面和相应障碍物设置静态(Navgation static),
调出Navgation面板
烘焙路径
二、创建寻路对象,挂载组件
如果想单独查看去某个位置的路线,人物不走动,将NavMeshAgent的Speed参数设置为0就可以。(本文设置为0演示)
三、编写代码
将如下代码挂载至人物对象上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Player : MonoBehaviour
{
private NavMeshAgent agent;
private LineRenderer line;
// Start is called before the first frame update
void Start()
{
agent = transform.GetComponent<NavMeshAgent>();
line = transform.GetComponent<LineRenderer>();
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 500))
{
if (hit.transform.tag == "plane")
{
agent.SetDestination(hit.point);
}
}
}
if (agent.path.corners.Length > 1)
{
line.positionCount = agent.path.corners.Length;
line.SetPositions(agent.path.corners);
}
}
}
实现效果如下:
四、创建编写相应Shader,添加材质至路径
Shader代码如下:
Shader "Custom/line"
{
Properties
{
MainTexture("Texture", 2D) = "white" {}
MoveSpeed("MoveSpeed", Range(0, 3)) = 1
}
SubShader
{
tags{"Queue" = "Transparent" "RenderType" = "Transparent" "IgnoreProjector" = "True"}
LOD 100
Blend SrcAlpha OneMinusSrcAlpha
Pass
{
Name "Simple"
Cull off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile_fog
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
UNITY_FOG_COORDS(1)
float4 vertex : SV_POSITION;
};
sampler2D MainTexture;
float4 MainTexture_ST;
float MoveSpeed;
v2f vert(appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, MainTexture);
UNITY_TRANSFER_FOG(o,o.vertex);
return o;
}
half4 frag(v2f i) : SV_Target
{
float2 uv = float2(i.uv.x - MoveSpeed * _Time.y,i.uv.y);
fixed4 col = tex2D(MainTexture, uv);
UNITY_APPLY_FOG(i.fogCoord, col);
return col;
}
ENDCG
}
}
}
材质贴图:
设置参数:
实现效果: