OnRenderObject: 在完成所有常规场景渲染后调用此函数。此时,可使用 GL 类或 Graphics.DrawMeshNow 绘制自定义几何图形。
C# 代码部分:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class huafu : MonoBehaviour
{
List<Vector3> PointList;
public Image image;
Texture2D texture;
// Start is called before the first frame update
void Start()
{
PointList = new List<Vector3>();
texture = new Texture2D(300, 400);// image.sprite.texture;
image.GetComponent<Image>().material.mainTexture = texture;
}
static Material lineMaterial;
static void CreateLineMaterial()
{
if (!lineMaterial)
{
// Unity has a built-in shader that is useful for drawing
// simple colored things.
Shader shader = Shader.Find("Hidden/Internal-Colored");//Custom/OutLine");
lineMaterial = new Material(shader);
lineMaterial.hideFlags = HideFlags.HideAndDontSave;
// Turn on alpha blending
lineMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
lineMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
// Turn backface culling off
lineMaterial.SetInt("_Cull", (int)UnityEngine.Rendering.CullMode.Off);
// Turn off depth writes
lineMaterial.SetInt("_ZWrite", 0);
}
}
public void OnRenderObject()
{
CreateLineMaterial();
// Apply the line material
lineMaterial.SetPass(0);
//正交投影
GL.LoadOrtho();
// Draw lines
if (PointList.Count > 2)
{
GL.Begin(GL.LINES);
for (int i = 0; i < PointList.Count-1; ++i)
{
GL.Color(Color.red);
GL.Vertex(PointList[i]);
GL.Vertex(PointList[i+1]);
}
GL.End();
}
// GLTrianGles2(myPoint2);
}
void GenerateTexture()
{
// texture = new Texture2D(300, 400);
for (int i = 0; i < PointList.Count-1; i++)
{
int XX = (int)(PointList[i].x * texture.width);
int YY = (int)(PointList[i].y * texture.height);
int XX1 = (int)(PointList[i+1].x * texture.width);
int YY1 = (int)(PointList[i+1].y * texture.height);
// 两点之间 做lerp插值
for (int j = 0; j < 80; j++)
{
int tmpXX =(int) Mathf.Lerp(XX, XX1, j / 80.0f);
int tmpYY = (int)Mathf.Lerp(YY, YY1, j / 80.0f);
texture.SetPixel(tmpXX, tmpYY, Color.red);
}
}
texture.Apply();
image.GetComponent<Image>().material.mainTexture = texture;
// GetComponent<Renderer>().material.mainTexture = texture;
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButton(0))
{
Debug.Log(Input.mousePosition+" "+ Screen.width);
Vector2 viewPos = Camera.main.ScreenToViewportPoint(Input.mousePosition);
if (PointList.Count == 0)
{
PointList.Add(viewPos);
}
else if (Input.mousePosition != PointList[PointList.Count - 1])
PointList.Add(viewPos);
}
if (Input.GetMouseButtonUp(0))
{
GenerateTexture();
PointList.Clear();
}
}
}