Projective-texture-mapping is used to project a Texture onto an object. By setting a camera on the projection point, get the VP matrix of the projection camera to get the UV coordinates relative to the texture. Detailed description: GPU programming and CG language Spring Snow lowbrow in section 12.3.
Shader"custom/projective-texture-mapping"{Properties {_tex ("Proj Tex", 2D) =" White"{} _color ("Main Color", Color) = (1,1,1,1) _ck ("Color Coef",float) =1} subshader {Pass {cgprogram #include"Unitycg.cginc" #pragmaVertex vert#pragmaFragment Fragsampler2d _tex; FLOAT4 _color; float_ck; float4x4 _texprojmat; structv2f {float4 pos:position; FLOAT4 shadowuv:texcoord0; FLOAT3 Normal:texcoord1; FLOAT3 Light:texcoord2; }; v2f Vert (Appdata_base v) {v2f o; O.pos=Mul (UNITY_MATRIX_MVP, V.vertex); FLOAT4 Worldpos=Mul (_object2world, V.vertex); O.shadowuv=Mul (_texprojmat, Worldpos); O.normal=V.normal; O.light=Objspacelightdir (V.vertex); returno; } float4 Frag (v2f i): COLOR {floatNL =dot (i.normal, i.light); Float2 UV= Float2 (i.shadowuv.x, I.SHADOWUV.Y)/I.SHADOWUV.W *0.5+0.5; if(Uv.x <0|| uv.x >1|| Uv.y <0|| Uv.y >1) return_CK * _color * MAX (0, NL); FLOAT4 T=tex2d (_tex, UV); return_CK * t * _color * MAX (0, NL); } ENDCG}} FallBack"Diffuse"}
The effect is as follows:
The code does not take into account the object's occlusion: The area behind the cube on the plane surface should be non-textured. To achieve this effect, the process of deep comparison should be added.
Unity shader:projective Texture Mapping