需求说明:Line是线段,把线段的首尾坐标存在Positions属性里。Element 0是首坐标,Element 1是尾坐标,但是Element 2是以Element 1为首坐标的尾坐标,也就是下一个元素是上一个元素的尾坐标,线段之间是相连的。
画图功能要求,鼠标左键按下时开始绘制线条,鼠标左键抬起时线条绘制完成。再次按下鼠标左键,又会开始绘制另一根线条,但跟上一根线条是不会自动相连的。所以,要实现不自动相连,就得每次绘制线条都重新生成一个Line。每个Line只要实现绘制一根线条的功能就好。所以分成两个脚本,Line挂载一个绘制一根线条的脚本。建一个空物体挂载生成Line,并把鼠标点传给Line的脚本。
1. 创建Line
2. 拖到 Project面板做成预制体
3. 写Line实现绘制一根线条的逻辑
1 public class DrawLine : MonoBehaviour 2 { 3 public LineRenderer lr; 4 public List<Vector3> points; 5 6 private void Awake() 7 { 8 lr = GetComponent<LineRenderer>(); 9 points = new List<Vector3>(); 10 } 11 12 public void Draw() 13 { 14 lr.positionCount = points.Count; 15 for (int i = 0; i < lr.positionCount; i++) 16 { 17 lr.SetPosition(i, points[i]); 18 } 19 } 20 }
4. 写生成Line的逻辑
1 public class NewLine : MonoBehaviour 2 { 3 GameObject line; 4 GameObject lineCp; 5 bool isDraw; 6 Color color = Color.black; 7 float width = 0.02f; 8 9 void Start() 10 { 11 line = Resources.Load("Prefabs/Line") as GameObject; 12 } 13 14 void Update() 15 { 16 if (Input.GetMouseButtonDown(0)) 17 { 18 isDraw = true; 19 lineCp = Instantiate(line); 20 } 21 if (Input.GetMouseButtonUp(0)) 22 isDraw = false; 23 if (isDraw) 24 { 25 Vector3 pos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 2); 26 pos = Camera.main.ScreenToWorldPoint(pos); //屏幕坐标转世界坐标 27 DrawLine dl = lineCp.GetComponent<DrawLine>(); //绘制每条线段的逻辑在DrawLine类里 28 dl.points.Add(pos); 29 dl.lr.startColor = color; 30 dl.lr.endColor = color; 31 dl.lr.startWidth = width; 32 dl.lr.endWidth = width; 33 dl.Draw(); 34 } 35 } 36 37 private void OnGUI() //设置一堆可以调节线条颜色和粗细的按钮 38 { 39 if (GUILayout.Button("红色")) 40 color = Color.red; 41 if (GUILayout.Button("黄色")) 42 color = Color.yellow; 43 if (GUILayout.Button("蓝色")) 44 color = Color.blue; 45 if (GUILayout.Button("绿色")) 46 color = Color.green; 47 if (GUILayout.Button("紫色")) 48 color = Color.magenta; 49 if (GUILayout.Button("黑色")) 50 color = Color.black; 51 if (GUILayout.Button("加粗")) 52 width += 0.02f; 53 if (GUILayout.Button("加细")) 54 width -= 0.02f; 55 } 56 }