1.创建矩形
注意:法线的方向,摄像机和光源的位置
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
public class GenerateQuad : MonoBehaviour
{
public float width = 10.0f; // 矩形的宽度
public float height = 5.0f; // 矩形的高度
public Material mat;
// Start is called before the first frame update
void Start()
{
Mesh mesh = new Mesh();
Vector3[] vertices = new Vector3[4]
{
new Vector3(-width / 2, -height / 2,10),
new Vector3(width / 2, -height / 2,10),
new Vector3(width / 2, height / 2,10),
new Vector3(-width / 2, height / 2,10)
};
mesh.vertices = vertices;
// 定义三角形的三角形面(索引)
int[] triangles = new int[6]
{
// 顶点顺序为顺时针
0, 1, 2,
2, 3, 0
};
mesh.triangles = triangles;
// 设置法线
Vector3[] normals = new Vector3[4]
{
Vector3.forward,
Vector3.forward,
Vector3.forward,
Vector3.forward
};
mesh.normals = normals;
// 设置UV坐标
Vector2[] uv = new Vector2[4]
{
new Vector2(0, 0),
new Vector2(1, 0),
new Vector2(1, 1),
new Vector2(0, 1)
};
mesh.uv = uv;
// 将创建的Mesh赋给MeshFilter组件
MeshFilter meshFilter = GetComponent<MeshFilter>();
meshFilter.mesh = mesh;
// 为MeshRenderer添加材质,这里需要一个使用顶点颜色的Shader
// 例如,使用"Particles/Additive" Shader
//Material material = new Material(Shader.Find("Particles/Standard Unlit"));
GetComponent<MeshRenderer>().material = mat;
transform.position = new Vector3(0,0,20);
transform.localScale = new Vector3(5,5,5);
}
}
2.建材质和shader
Shader "Custom/quadCol"
{
Properties
{
_Color("Main Color",Color) = (1,1,1,1)
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
float4 _Color;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
fixed4 frag (v2f i) : SV_Target
{
fixed4 col = lerp(_Color,fixed4(0, 1, 1, 1),i.uv.x);
return col;
}
ENDCG
}
}
}
3.运行效果如下