Unity Shader案例之——阴阳师画符效果

  本来这边文章是在阴阳师刚出来的时候打算写的,结果一直丢在草稿箱里没有完善,今天得空从草稿箱里拿出来重新来过。还记得玩阴阳师的时候大家每次最激动的时候就是抽卡,每次都画各种各样的图案,总以为最特别的方案能更大概率的抽到"SSR",尽管结果可能不尽人意,但是这种抽卡方式的确有他的乐趣所在。今天就来实现:如何将屏幕上画的图案显示在其他物体上


首先来理一下思路,这个功能可以分为两部分。第一部:如何在屏幕上画图案;第二部:如何将屏幕上的图案保存为Texture2D,然后赋给物体。


关于第一个问题可以看这里:屏幕画线


我们直接来看第二个问题,将图片保存为Texture2D,这里方法也很多:

1.可以将camera的RenderTexture保存为Texture2D;

2.也可以用一个后处理的RenderTexture;

3.甚至还可以用shader的GrabTexture。


方法3的缺点是只能全屏截图,而1,2可以自定义截取的区域大小,具体实现:

      Texture2D png = new Texture2D(rt.width, rt.height, TextureFormat.ARGB32, false);
      png.ReadPixels(new Rect(0, 0, width, height), 0, 0);//这里修改Rect控制截图区域
博主比较懒,直接用一个Shader实现所有功能:

Shader "Custom/CombineTexture"
{
	Properties
	{
		_TintColor ("Tint Color", Color) = (1.0, 1.0, 1.0, 1.0)
		_MainTexure ("Main Texure", 2D) = "white" {}
		_GrabTexure ("Grab Texure", 2D) = "white" {}
	}

	SubShader 
	{
		Tags { "RenderType"="Opaque" "Queue"="Geometry"}

		Pass
		{
			CGPROGRAM
		
			#pragma vertex vert
			#pragma fragment frag

			#include "UnityCG.cginc"
			#include "Lighting.cginc"

			struct a2v
			{
				half4 vertex : POSITION;
				half3 normal : NORMAL;
				fixed4 texcoord : TEXCOORD0;
			};

			struct v2f
			{
				half4 pos : SV_POSITION;
				float2 uv : TEXCOORD0; 
				half3 normal : TEXCOORD1;
				half3 lightDir : TEXCOORD2 ;
			};

			fixed4 _TintColor;
			sampler2D _MainTexure;
			float4 _MainTexure_ST;
			sampler2D _GrabTexure;

			v2f vert(a2v v)
			{
				v2f o;
				o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
				o.uv = TRANSFORM_TEX (v.texcoord, _MainTexure);
				o.normal = normalize(UnityObjectToWorldNormal(v.normal));
				o.lightDir = normalize(UnityWorldSpaceLightDir(v.vertex));

				return o;
			}

			fixed4 frag(v2f i) : COLOR
			{
				fixed3 mainCol = tex2D(_MainTexure, i.uv).rgb;
				fixed3 grabCol = tex2D(_GrabTexure, i.uv).rgb;
				mainCol = lerp(mainCol, grabCol, grabCol.r);

				float d = dot(i.normal,i.lightDir);
				d = 1 - (d * 0.5 + 0.5);

				fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz;
				fixed3 finalCol =_LightColor0.rgb * (_TintColor.rgb + grabCol) * mainCol * d + ambient;

				return fixed4(finalCol,1);
			}

			ENDCG
		}
	}
	FallBack "VertexLit"
}

最终效果:

博主的字写的是不是很标准,哈哈,因为我是输入法打的字/斜眼笑。是不是很简单,希望下次可以看到你做的抽"SSR"的游戏哦!

猜你喜欢

转载自blog.csdn.net/u013917120/article/details/53586734