功能:实现一个模型在指定屏幕坐标中的渲染,不在的裁剪掉
效果:
GroudX和GroudY都为0时:
调整数值后:
原理,得到模型在屏幕中的坐标传入片面着色器时,判断下顶点坐标是否在指定区域内,不在的顶点直接裁剪掉
源码:
Shader "Unlit/NewUnlitShader"{Properties{_MainTex ("Texture", 2D) = "white" {}_GroudX("GroudX",Range(0,0.5))=0 //X方向距离左右边框的百分比 在这之内的都会裁剪掉_GroudY("GroudY",Range(0,0.5))=0 //Y方向距离左右边框的百分比}SubShader{Tags {"RenderType"="Opaque" }LOD 100Pass{CGPROGRAM#pragma vertex vert#pragma fragment frag// make fog work#pragma multi_compile_fog#include "UnityCG.cginc"struct appdata{float4 vertex : POSITION;float2 uv : TEXCOORD0;};struct v2f{float2 uv : TEXCOORD0;UNITY_FOG_COORDS(1)float4 vertex : SV_POSITION;float4 screenPos : TEXCOORD1;};sampler2D _MainTex;float4 _MainTex_ST;float _GroudX;float _GroudY;v2f vert (appdata v){v2f o;o.vertex = UnityObjectToClipPos(v.vertex);o.uv = TRANSFORM_TEX(v.uv, _MainTex);UNITY_TRANSFER_FOG(o,o.vertex);o.screenPos=ComputeScreenPos (o.vertex);//得到屏幕坐标百分比return o;}fixed4 frag (v2f i) : SV_Target{fixed4 col = tex2D(_MainTex, i.uv);UNITY_APPLY_FOG(i.fogCoord, col);float2 screenPos =i.screenPos.xy/i.screenPos.w;if(screenPos.x>_GroudX&&screenPos.x<(1-_GroudX)&&screenPos.y>_GroudY&&screenPos.y<(1-_GroudY)){}else{discard;}return col;}ENDCG}}}