項目中有在場景模型上做標記線的需求,其實遊戲內很多光投影,角色的陰影,手電筒等效果都可以通過Projector來實現。Unity Standard Assets 裏有Projector的組件和預製體,這裏我們也是修改下projector的shader,讓它更符合我們的項目需求。
Shader "Projector/ray"
{
Properties
{
_Color ("Color", Color) = (1,1,1,1)
_MainTex ("Cookie", 2D) = "white" {}
}
SubShader
{
Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" "PreviewType"="Plane" }
Pass
{
ColorMask RGB
ZWrite off Cull Off Lighting Off
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile_fog
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
UNITY_FOG_COORDS(1)
float4 vertex : SV_POSITION;
float4 texc:TEXCOORD1;
};
sampler2D _MainTex;
float4 _MainTex_ST;
float4x4 unity_Projector;
fixed4 _Color;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
o.texc = mul(unity_Projector, v.vertex);
UNITY_TRANSFER_FOG(o,o.vertex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
float4 c = tex2Dproj(_MainTex, i.texc) * _Color;
UNITY_APPLY_FOG(i.fogCoord, col);
return c;
}
ENDCG
}
}
}
創建材質然後選擇Projector/ray的shader :
然後就是Cookie圖片的選擇,這裏我們就用一個白條的圖片即可,圖片屬性設置如下:
接下來就是項目中引用了, 在一個空的GameObject上引用Projector,然後調節相應的投射參數,此處注意可通過IgnoreLayers來篩選投射的物體。示例如下:
全部設置完畢,再找一個Cube做投射試驗,效果如下:
這只是項目內使用Projector的一個小例子,更多的功能使用後續再做總結了。