1.代码
Shader "Custom/FishEye"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_DistortionAmount ("Distortion Amount", Range(0, 1)) = 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 _DistortionAmount;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
float2 FishEyeDistortion(float2 uv, float amount)
{
float2 center = float2(0.5, 0.5);
float2 delta = uv - center;
float dist = length(delta);
float factor = pow(dist, amount);
return center + delta * factor;
}
fixed4 frag (v2f i) : SV_Target
{
// Apply the distortion
float2 distortedUv = FishEyeDistortion(i.uv, _DistortionAmount);
// Sample the texture
fixed4 col = tex2D(_MainTex, distortedUv);
return col;
}
ENDCG
}
}
}
效果:
2.参数方程实现
Shader "Custom/FishEye"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_DistortionFactor ("Distortion Factor", Range(-2, 2)) = 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 _DistortionFactor;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
float2 DistortCoordinates(float2 uv, float factor)
{
float2 center = float2(0.5, 0.5);
uv -= center;
float r = length(uv);
float theta = atan2(uv.y, uv.x);
// Apply the distortion equation
float rDistorted = r * (1.0 - factor * r * r);
// Convert back to Cartesian coordinates
return float2(rDistorted * cos(theta), rDistorted * sin(theta)) + center;
}
fixed4 frag (v2f i) : SV_Target
{
// Apply the distortion
float2 distortedUv = DistortCoordinates(i.uv, _DistortionFactor);
// Sample the texture
fixed4 col = tex2D(_MainTex, distortedUv);
return col;
}
ENDCG
}
}
}
效果: