首页 > 技术文章 > 广告牌

mcyushao 2019-04-28 22:28 原文

Shader "Unlit/Billboard"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_Color("Color Tint",Color) = (1,1,1,1)
_VerticalBillboarding("Vertical Restraints",Range(0,1)) = 1
}
SubShader
{
Tags{ "Queue" = "Transparent" "IgnoreProjector" = "True" "RenderType" = "Transparent" "DisableBatching" = "True" }
Pass
{
Tags{ "LightMode" = "ForwardBase" }
ZWrite Off
Blend SrcAlpha OneMinusSrcAlpha
Cull Off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "Lighting.cginc"
sampler2D _MainTex;
float4 _MainTex_ST;
float4 _Color;
float _VerticalBillboarding;
struct a2v
{
float4 vertex : POSITION;
float4 texcoord : TEXCOORD0;
};
struct v2f
{
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
};
v2f vert(a2v v)
{
float3 center = float3(0,0,0);//预设中心为0,0,0
float3 viewer = mul(unity_WorldToObject,float4(_WorldSpaceCameraPos,1));//将世界空间的摄像机位置转化到模型空间
float3 normalDir = viewer - center;//法线方向
normalDir.y = normalDir.y * _VerticalBillboarding;//选择哪个方向是固定的
normalDir = normalize(normalDir);//归一化
float3 upDir = abs(normalDir.y) > 0.999 ? float3(0, 0, 1) : float3(0,1,0);//如果法线方向y是1,则up方向z是1
float3 rightDir = normalize(cross(upDir, normalDir));//叉积求出右方向
upDir = normalize(cross(normalDir,rightDir));//通过右方向和法线方向求出准确的上方向
float3 centerOffs = v.vertex.xyz - center;
float3 localPos = center + rightDir*centerOffs.x + upDir * centerOffs.y + normalDir * centerOffs.z;
v2f o;
o.pos = UnityObjectToClipPos(float4(localPos,1));
o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
return o;
}
fixed4 frag(v2f i) : SV_Target
{
fixed4 c = tex2D(_MainTex,i.uv);
c.rgb *= _Color.rgb;
return c;
//return fixed4(ambient + diffuse, 1.0);
}
ENDCG
}
}
}

推荐阅读