1. 程式人生 > >Unity3D 畫筆實現系列01-LineRender

Unity3D 畫筆實現系列01-LineRender

opened bject array use 簡單 ade world bezier shade

前言:剛從Python轉到U3D時,第一個項目涉及到畫線,剛開始想那還不簡單嗎,不就是獲取位置後著色嗎,H5中的Canvas就能實現,當我看了Unity的文檔後一臉懵逼,居然沒有相關的方法。沒辦法只能在網上找,涉及到畫線的很多,各種坑。

Unity畫線最簡單的實現方法LineRender組件:

LineRender實現起來比較簡單,

技術分享圖片
 1 public class line : MonoBehaviour
 2 {
 3     /*
 4      LineRenderer畫線優點是簡單,易控制,在移動端效果較好
 5      缺點:1.線寬不能高度定制(毛筆效果不好實現),
6 2.不能重復貼圖(蠟筆)(2017版本後貼圖可以重復但效果不是很好--Texture Mode 設置成repeat), 7 3,橡皮擦實習起來比較復雜: 8 1.再用一個LineRenderer畫白色線條 9 2.把圖片渲染到RendererTexture上 10 3.利用shader扣掉白色(缺點不能畫白色) 11 4,保存方法自能截圖 12 5,保存恢復記錄的東西太多了 13 */ 14 private GameObject lineRendererObj;
15 private LineRenderer lineRenderer; 16 private List<Vector3> worldPos = new List<Vector3>(); 17 public GameObject lineRendererPre; 18 private bool moving; 19 private void Update() 20 { 21 22 #region 畫筆 23 if (Input.GetMouseButtonDown(0))
24 { 25 moving = true; 26 InitLine(Color.red); 27 28 } 29 if (Input.GetMouseButtonUp(0)) 30 { 31 moving = false; 32 worldPos.Clear(); 33 } 34 #endregion 35 36 37 38 #region 橡皮 39 if (Input.GetMouseButtonDown(1)) 40 { 41 moving = true; 42 InitLine(Color.white); 43 44 } 45 if (Input.GetMouseButtonUp(1)) 46 { 47 moving = false; 48 worldPos.Clear(); 49 } 50 #endregion 51 if (moving) 52 { 53 Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);//取得點擊點的世間坐標 54 pos.z = 0;//設置為0效果更好 55 if (worldPos.Count > 1) 56 { 57 if (Vector3.Distance(pos, worldPos[worldPos.Count - 1]) < 0.08f) 58 { 59 return; 60 } 61 } 62 63 worldPos.Add(pos); 64 Draw(); 65 //BezierPathDraw();//貝塞爾曲線優化畫筆效果差別不大,很卡 66 67 } 68 } 69 70 private void InitLine(Color color) 71 { 72 lineRendererObj = Instantiate(lineRendererPre, this.transform); 73 lineRenderer = lineRendererObj.GetComponent<LineRenderer>(); 74 lineRenderer.numCapVertices = 5;//控制在結尾處添加的點數越多越圓滑 75 lineRenderer.numCornerVertices = 5;//控制在折角處添加的點數越多越圓滑 76 lineRenderer.startColor = color;//開始的顏色 77 lineRenderer.endColor = color;//結束的顏色 78 lineRenderer.startWidth = 0.2f;//開始的寬度 79 lineRenderer.endWidth = 0.2f;//結束的寬度 80 } 81 private void Draw() 82 { 83 lineRenderer.positionCount = worldPos.Count; 84 lineRenderer.SetPositions(worldPos.ToArray()); 85 }
View Code

Unity3D 畫筆實現系列01-LineRender