在Unity中,你可以使用OpenGL的即时模式(Immediate Mode)或着色器来实时绘制矩形。然而,从Unity 5.x开始,Unity推荐使用着色器和材质来绘制图形,因为这种方式更加高效且符合现代图形编程的范式。以下是一个使用着色器和材质在Unity中实时绘制矩形的示例:
1. 创建着色器
首先,你需要创建一个简单的着色器来绘制矩形。在Unity中,创建一个新的着色器文件(例如命名为SimpleRectShader.shader
),并编写如下代码:
glsl复制代码
Shader "Custom/SimpleRectShader" | |
{ | |
Properties | |
{ | |
_Color ("Color", Color) = (1,1,1,1) | |
} | |
SubShader | |
{ | |
Tags { "RenderType"="Opaque" } | |
LOD 100 | |
Pass | |
{ | |
CGPROGRAM | |
#pragma vertex vert | |
#pragma fragment frag | |
// make fog work | |
#pragma multi_compile_fog | |
#include "UnityCG.cginc" | |
struct appdata | |
{ | |
float4 vertex : POSITION; | |
}; | |
struct v2f | |
{ | |
float2 uv : TEXCOORD0; | |
UNITY_FOG_COORDS(1) | |
float4 vertex : SV_POSITION; | |
}; | |
fixed4 _Color; | |
v2f vert (appdata v) | |
{ | |
v2f o; | |
o.vertex = UnityObjectToClipPos(v.vertex); | |
UNITY_TRANSFER_FOG(o,o.vertex); | |
return o; | |
} | |
fixed4 frag (v2f i) : SV_Target | |
{ | |
// sample the texture | |
fixed4 col = _Color; | |
UNITY_APPLY_FOG(i.fogCoord, col); | |
return col; | |
} | |
ENDCG | |
} | |
} | |
} |
这个着色器定义了一个简单的顶点着色器vert
和一个片段着色器frag
,它们会绘制一个单一颜色的矩形。
2. 创建材质
接下来,你需要创建一个材质来使用这个着色器。在Unity的Project窗口中,右键点击 -> Create -> Material,然后将新创建的材质命名为SimpleRectMaterial
。在材质的Inspector窗口中,将Shader属性设置为刚才创建的SimpleRectShader
。
3. 编写脚本以绘制矩形
现在,你需要编写一个脚本来实时绘制矩形。创建一个新的C#脚本(例如命名为DrawRectScript.cs
),并编写如下代码:
csharp复制代码
using UnityEngine; | |
public class DrawRectScript : MonoBehaviour | |
{ | |
public Material rectMaterial; // Assign this in the inspector with your material | |
public Vector2 rectSize = new Vector2(1, 1); // Size of the rectangle | |
public Vector2 rectPosition = new Vector2(0, 0); // Position of the rectangle | |
private void OnPostRender() | |
{ | |
if (!rectMaterial) | |
{ | |
Debug.LogError("Please assign a material in the inspector."); | |
return; | |
} | |
// Setup the GPU state | |
GL.PushMatrix(); | |
GL.LoadOrtho(); | |
// Set the material | |
rectMaterial.SetPass(0); | |
// Draw the rectangle | |
GL.Begin(GL.QUADS); // Start drawing a quad (rectangle) | |
GL.Color(Color.white); // Set the color to white (you can change this or use your material's color) | |
GL.Vertex3(rectPosition.x, rectPosition.y, 0); // Bottom left | |
GL.Vertex3(rectPosition.x + rectSize.x, rectPosition.y, 0); // Bottom right | |
GL.Vertex3(rectPosition.x + rectSize.x, rectPosition.y + rectSize.y, 0); // Top right | |
GL.Vertex3(rectPosition.x, rectPosition.y + rectSize.y, 0); // Top left | |
GL.End(); // End drawing the quad | |
// Restore the GPU state | |
GL.PopMatrix(); | |
} | |
} |
在这个脚本中,我们使用了Unity的GL类来直接绘制一个四边形(即矩形)。OnPostRender
方法确保在场景中的所有其他渲染完成后才执行我们的绘制代码。GL.PushMatrix
和GL.PopMatrix
用于保存和恢复当前的GPU矩阵状态。GL.LoadOrtho
设置了一个正交投影,这对于2D渲染非常有用。