unity画线之映射到3D物体上

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);
        }
    }
}

测试结果:

猜你喜欢

转载自blog.csdn.net/u012909508/article/details/85002793