在2018版的unity引擎中写一个图片从四周慢慢向中心虚化的shader,能够手动控制虚化的强度和范围
时间: 2023-11-27 12:54:07 浏览: 21
在Unity中编写一个图片从四周慢慢向中心虚化的着色器(shader),可以手动控制虚化的强度和范围,可以参照以下的代码实现:
```
Shader "Custom/CenterBlur" {
Properties {
_MainTex ("Texture", 2D) = "white" {}
_BlurRange ("Blur Range", Range(0.0, 5.0)) = 1.0
_BlurStrength ("Blur Strength", Range(0.0, 1.0)) = 0.5
}
SubShader{
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;
float _BlurRange;
float _BlurStrength;
v2f vert (appdata v) {
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
fixed4 frag (v2f i) : SV_Target {
float4 sum = 0;
float4 centerColor = tex2D(_MainTex, i.uv);
float4 color;
float totalWeight = 0;
// Loop through pixels in a square around the center pixel
for (int x = -10; x <= 10; x++) {
for (int y = -10; y <= 10; y++) {
float2 offset = float2(x, y);
float weight = 1 - (length(offset) / _BlurRange);
weight = saturate(weight * _BlurStrength);
color = tex2D(_MainTex, i.uv + offset / _ScreenParams.zw);
sum += color * weight;
totalWeight += weight;
}
}
// Combine center color and blurred color
float4 blurredColor = sum / totalWeight;
return lerp(centerColor, blurredColor, _BlurStrength);
}
ENDCG
}
}
FallBack "Diffuse"
}
```
在这个着色器中,我们使用两个属性 `_BlurRange` 和 `_BlurStrength` 来控制虚化的强度和范围。在 `frag` 函数中,我们循环遍历中心像素周围的像素,并计算每个像素的权重。然后用这些权重来计算虚化后的颜色。
最后,使用 `lerp` 函数将中心像素的颜色和虚化后的颜色结合起来,得到最终的颜色。