Unity 用Material画出一条指示路径
最近项目有需要画一条可以动的路径 路径的位置是服务器给的 就想起来用Material来实现。
大概原理就是:
1. 创建一个Plane;
2.根据提供的起点和终点坐标 把Plane放置在两点中间的位置
3.控制Material的offset 来让Material 的贴图呈现动的效果
4.根据两点间的距离 修改Material的Tiling 来调整间隔距离
5.根据两点间距 修改Plane的localScaler Z的大小 来调整路径显示的长度
下面代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TestRoute : MonoBehaviour { public Vector2 Interval = new Vector2(0, -0.02f); /// <summary> /// 旋转方向 /// </summary> public Transform point; private Material material; private Vector2 offset; void Start() { material = this.GetComponent<MeshRenderer>().material; offset = Vector2.zero; // Test(); } // Update is called once per frame void Update() { offset -= Interval; material.SetTextureOffset("_MainTex", offset); } /// <summary> /// 设置Route 位置 长度 朝向 旋转 /// </summary> /// <param name="endPos"></param> /// <param name="exitPos"></param> public void SetRoute( Vector3 endPos, Vector3 exitPos ) { if (material == null) material = this.GetComponent<MeshRenderer>().material; Debug.Log("Route " + endPos + " "+ exitPos); //GameObject obj = new GameObject("A"); //obj.transform.position = endPos; //obj = new GameObject("B"); //obj.transform.position = exitPos; //Vector3 middle = (endPos - exitPos) / 2; //transform.position = endPos - middle; transform.localScale += new Vector3(0, 0, Mathf.Abs( Vector3.Distance(endPos,exitPos) )/11f); material.SetTextureScale("_MainTex", new Vector2(1, Mathf.Abs(Vector3.Distance(endPos, exitPos))*1.5f)); //Debug.Log((exitPos - endPos).normalized); // transform.rotation = Quaternion.LookRotation(transform.position, (endPos - exitPos).normalized); Vector3 pos = endPos + (exitPos - endPos).normalized * (Vector3.Distance(endPos, exitPos)); transform.position = (exitPos+endPos)/2.0f + new Vector3(0, -1.5f, 0); point.position = endPos + new Vector3(0, transform.position.y, 0); transform.LookAt(point); //transform.eulerAngles = new Vector3(0, transform.eulerAngles.y+182 , 0); } /* * TEST * * * */ public Transform A; public Transform B; public void Test() { SetRoute(A.position, B.position); } }