之前做了一个爆散的效果,那是利用已有顶点的偏移来实现。今天做的增厚效果则是将已有的顶点复制出来一个,然后沿法线方向偏移,形成双层结构,让最终绘制出来的图像有一定的厚度。
代码:
Shader "MyShader/SS_14"
{
Properties{
_MainTex("Texture", 2D) = ""{}
_Mask("Mask", 2D) = ""{}
}
SubShader
{
CGINCLUDE
#include "UnityCG.cginc"
sampler2D _MainTex;
sampler2D _Mask;
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
float3 normal : NORMAL;
};
struct v2f
{
float4 vertex : SV_POSITION;
float2 uv : TEXCOORD0;
float4 worldPos : TEXCOORD1;
float3 normal : TEXCOORD2;
};
float3 twist(float3 p, float3 center, float power) {
float t = _Time.y*2;
if (t > 360) {
t -= 360;
}
float s = sin(power*t);
float c = cos(power*t);
float3x3 m = float3x3(
c, -s, 0,
s, c, 0,
0, 0, 1
);
return mul(m, p - center);
}
v2f vert(appdata v)
{
v2f o;
o.vertex = v.vertex;
o.uv = v.uv;
o.worldPos = mul(unity_ObjectToWorld, v.vertex);
o.normal = v.normal;
return o;
}
#define ADD_VERT(v,_uv) \
o.vertex = UnityObjectToClipPos(v);\
o.uv=_uv;\
tristream.Append(o);
#define ADD_TRI(p0, p1, p2,uv0,uv1,uv2) \
ADD_VERT(p0,uv0) \
ADD_VERT(p1,uv1) \
ADD_VERT(p2,uv2) \
tristream.RestartStrip();
[maxvertexcount(30)]
void geom(triangle v2f v[3], inout TriangleStream<v2f> tristream)
{
v2f o = v[0];
float3 edgeA = v[1].vertex.xyz - v[0].vertex.xyz;
float3 edgeB = v[2].vertex.xyz - v[0].vertex.xyz;
float3 normal = normalize(cross(edgeA, edgeB))*0.1; //法线
float3 center = ((v[0].vertex.xyz + v[1].vertex.xyz + v[2].vertex.xyz)/ 3+normal);
//float4 _height=tex2D(_Mask,v[0].uv); //会报错:cannot map expression to gs_4_0 instruction set(因为颜色采样只能在frag中进行)
float3 v0 = v[0].vertex.xyz;
float3 v1 = v[1].vertex.xyz;
float3 v2 = v[2].vertex.xyz ;
float3 v3 = (v[0].vertex.xyz + normal);
float3 v4 =(v[1].vertex.xyz + normal);
float3 v5 =(v[2].vertex.xyz + normal);
v0 = twist(v0, center, 1) + center;
v1 = twist(v1, center, 1) + center;
v2 = twist(v2, center, 1) + center;
v3 = twist(v3, center, 1) + center;
v4 = twist(v4, center, 1) + center;
v5 = twist(v5, center, 1) + center;
float2 suv0 = v[0].uv;
float2 suv1 = v[1].uv;
float2 suv2 = v[2].uv;
float2 suv3 = v[0].uv;
float2 suv4 = v[1].uv;
float2 suv5 = v[2].uv;
//这一块要根据三角面的绘制顺序
ADD_TRI(v2, v5, v1, suv2, suv5, suv1);
ADD_TRI(v2, v1, v0, suv2, suv1, suv0);
ADD_TRI(v1, v4, v0, suv1, suv4, suv0);
ADD_TRI(v4, v3, v0, suv4, suv3, suv0);
ADD_TRI(v0, v3, v2, suv0, suv3, suv2);
ADD_TRI(v5, v4, v1, suv5, suv4, suv1);
ADD_TRI(v3, v5, v2, suv3, suv5, suv2);
ADD_TRI(v5, v3, v4, suv5, suv3, suv4);
}
fixed4 frag(v2f i) : SV_Target
{
return tex2D(_MainTex, i.uv);
}
ENDCG
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma geometry geom
#pragma fragment frag
ENDCG
}
}
}
本来准备用一张额外的图来实现不同的厚度,但是没成功,就做了一个旋转效果。
返回目录:https://blog.csdn.net/yzy1987523/article/details/106676451