unity畫線之對映到3D物體上
阿新 • • 發佈:2018-12-21
1.畫線方式有很多
包括OpenGL,shader ,linerender,也可以直接動態更改貼圖的畫素點顏色
這裡是用的GL,如果不是太懂gl的可以參考unity 官方API,其實我也不是太懂~~~~
using UnityEngine; using System.Collections.Generic; public class Painting : MonoBehaviour { List<Vector2> mDrawPoints = new List<Vector2>(); private void Update() { if (Input.GetMouseButton(0)) { Vector2 tmpPos = Camera.main.ScreenToViewportPoint(Input.mousePosition); mDrawPoints.Add(tmpPos); } if (Input.GetMouseButtonUp(0)) { PaintingSymbol(); //清空螢幕上的點 mDrawPoints.Clear(); } } public void PaintingSymbol() { Texture2D tmpTex = new Texture2D(600, 800); for (int i = 1; i < mDrawPoints.Count; i++) { Vector2 tmpFront = mDrawPoints[i - 1]; Vector2 tmpBack = mDrawPoints[i]; for (int j = 1; j < 80; j++) { int TempX = (int)(Mathf.Lerp(tmpFront.x * tmpTex.width, tmpBack.x * tmpTex.width, j / 80f)); int TempY = (int)(Mathf.Lerp(tmpFront.y * tmpTex.height, tmpBack.y * tmpTex.height, j / 80f)); tmpTex.SetPixel(TempX, TempY, Color.red); } } tmpTex.Apply(); this.GetComponent<Renderer>().material.mainTexture = tmpTex; } //在所有常規渲染完成後將呼叫 public void OnRenderObject() { CreateLineMaterial(); //應用線條材質 lineMaterial.SetPass(0); GL.PushMatrix(); // Set transformation matrix for drawing to // match our transform GL.MultMatrix(transform.localToWorldMatrix); // Draw lines GL.Begin(GL.LINES); // 將透視投影變成正交投影 GL.LoadOrtho(); GL.Color(Color.red); for (int i = 1; i < mDrawPoints.Count; i++) { Vector2 tmpFront = mDrawPoints[i - 1]; Vector2 tmpBack = mDrawPoints[i]; GL.Vertex3(tmpFront.x, tmpFront.y, 0); GL.Vertex3(tmpBack.x, tmpBack.y, 0); } GL.End(); GL.PopMatrix(); } static Material lineMaterial; static void CreateLineMaterial() { if (!lineMaterial) { //Unity有一個內建的著色器,可用於繪圖 //簡單的有色物品。 Shader shader = Shader.Find("Hidden/Internal-Colored"); lineMaterial = new Material(shader); lineMaterial.hideFlags = HideFlags.HideAndDontSave; // 開啟alpha混合 lineMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); lineMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); //關閉背面剔除 lineMaterial.SetInt("_Cull", (int)UnityEngine.Rendering.CullMode.Off); //關閉深度寫入 lineMaterial.SetInt("_ZWrite", 0); } } }
測試結果: