话不多说,将以下shader赋给材质贴上贴图即可。
Shader "HQY/Shader2" //自己改名
{
Properties
{
_Diffuse ("Diffuse", Color) = (1,1,1,1)
_MainTex ("MainTex", 2D) = "white" {}
_Specular("Specular", Color) = (1,1,1,1)
_Gloss("Gloss", Range(8,256)) = 20
_PixelSize ("PixelSize", Range(1, 100)) = 1
}
SubShader
{
Tags { "RenderType"="Opaque" "LightMode"="ForwardBase"}
LOD 200
Pass{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "Lighting.cginc"
fixed4 _Diffuse;
sampler2D _MainTex;
sampler2D _NewTex;
fixed4 _Specular;
float _Gloss;
struct appdata {
float4 vertex : POSITION;
float3 normal : NORMAL;
float2 texcoord : TEXCOORD0;
float2 uv : TEXCOORD0;
};
struct v2f {
float4 pos : SV_POSITION;
float3 worldNormal : TEXCOORD0;
float3 worldPos : TEXCOORD1;
float2 uv : TEXCOORD2;
};
v2f vert (appdata v) {
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.worldNormal = UnityObjectToWorldNormal(v.normal);
o.worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
o.uv = v.uv;
return o;
}
float4 _MainTex_TexelSize;
float _PixelSize;
fixed4 frag (v2f i) : SV_TARGET {
float2 interval = _PixelSize * _MainTex_TexelSize.xy;
float2 th = i.uv / interval; // 按interval划分中,属于第几个像素
float2 th_int = floor(th); // 去小数,让采样的第几个纹素整数化,这就是失真UV关键
th_int *= interval; // 再重新按第几个像素的uv坐标定位
//return tex2D(_MainTex, th_int); //若不需叠加光影则直接返回
fixed4 texColor = tex2D(_MainTex, th_int);
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.rgb * texColor.rgb;
fixed3 diffuse = _LightColor0.rgb * texColor.rgb * max(0, dot(i.worldNormal, _WorldSpaceLightPos0.xyz));
fixed3 specular = _LightColor0.rgb * _Specular.rgb * pow(max(0, dot(reflect(_WorldSpaceLightPos0.xyz, i.worldNormal), normalize(i.worldPos - _WorldSpaceCameraPos))), _Gloss);
fixed4 c = fixed4(ambient + diffuse + specular, 1.0);
c *= _Diffuse;
return c;
}
ENDCG
}
}
FallBack "Diffuse"
}
效果如下:
至于光影效果的像素化与贴图配套,除了建立贴图UV与片元法线等的映射,还可以将光照情况预先烘焙至贴图,然后再将贴图像素化。