用Unity写一个描边shader
时间: 2023-06-13 07:04:21 浏览: 147
unity 描边Shader
4星 · 用户满意度95%
下面是一个简单的Unity描边shader的示例代码:
```
Shader "Custom/Outline" {
Properties {
_MainTex ("Texture", 2D) = "white" {}
_OutlineColor ("Outline Color", Color) = (0,0,0,1)
_OutlineWidth ("Outline Width", Range (0.002, 0.1)) = 0.01
}
SubShader {
Tags {"Queue"="Transparent" "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;
};
sampler2D _MainTex;
float4 _MainTex_ST;
float4 _OutlineColor;
float _OutlineWidth;
v2f vert (appdata v) {
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
return o;
}
fixed4 frag (v2f i) : SV_Target {
// sample the texture
fixed4 col = tex2D(_MainTex, i.uv);
// calculate the outline color
fixed4 outline = _OutlineColor;
float2 texelSize = 1.0 / _ScreenParams.xy;
float2 offset[4] = float2[](
float2(texelSize.x, 0),
float2(-texelSize.x, 0),
float2(0, texelSize.y),
float2(0, -texelSize.y)
);
for (int j = 0; j < 4; j++) {
outline += tex2D(_MainTex, i.uv + _OutlineWidth * offset[j]);
}
outline /= 5.0;
// mix the texture and outline color
return lerp(outline, col, col.a);
}
ENDCG
}
}
FallBack "Diffuse"
}
```
这个shader的核心思想是在每个像素周围采样一些颜色,并将它们平均值作为描边颜色。可以通过调整 `_OutlineWidth` 属性来控制描边的宽度,通过调整 `_OutlineColor` 属性来控制描边的颜色。
阅读全文