码迷,mamicode.com
首页 > 编程语言 > 详细

Unity2D实现贴图凹凸感并接受实时光照效果

时间:2015-07-03 17:25:52      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:unity   shader   2d   光影   凹凸   

先看最终效果:

技术分享技术分享

我们的原图是一个3D模型的截图:

技术分享


这一效果是通过Shader实现的:

(Shader代码来自国外博客:http://www.thomas-joncorpuz.com/blog/2014/11/30/custom-unity-2d-sprite-shader)

Shader "Custom/SpriteNormal" {
	 Properties
    {
        [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
        _NormalsTex ("Sprite Normals", 2D) = "bump" {}
        _Ramp ("Shading Ramp", 2D) = "white" {}
        _Color ("Tint", Color) = (1,1,1,1)
        [MaterialToggle] PixelSnap ("Pixel snap", Float) = 0
        _Cutoff ("Alpha Cutoff", Range (0,1)) = 0.5
    }

    SubShader
    {
        Tags
        { 
            "Queue"="Transparent" 
            "IgnoreProjector"="False" 
            "RenderType"="Transparent" 
            "PreviewType"="Plane"
            "CanUseSpriteAtlas"="True"
        }

        Cull Off
        Lighting On
        ZWrite Off
        Fog { Mode Off }
        Blend SrcAlpha OneMinusSrcAlpha

        CGPROGRAM
        #pragma surface surf CustomLambert alpha vertex:vert addshadow alphatest:_Cutoff 
        #pragma multi_compile DUMMY PIXELSNAP_ON

        sampler2D _MainTex;
        sampler2D _NormalsTex;
        sampler2D _Ramp;
        fixed4 _Color;

        struct Input
        {
            float2 uv_MainTex;
            fixed4 color;
        };
        
        half4 LightingCustomLambert (SurfaceOutput s, half3 lightDir, half3 viewDir, half atten) {
            half NdotL = dot (s.Normal, lightDir);
            half4 c;
            c.rgb = (s.Albedo * _LightColor0.rgb * (tex2D (_Ramp, half2 (NdotL * 0.5 + 0.5, 0)))) * (atten * 2);
            c.a = s.Alpha;
            return c;
        }
        
        void vert (inout appdata_full v, out Input o)
        {
            #if defined(PIXELSNAP_ON) && !defined(SHADER_API_FLASH)
            v.vertex = UnityPixelSnap (v.vertex);
            #endif
            v.normal = float3(0,0,-1);
            v.tangent = float4(-1, 0, 0, 1);
            
            UNITY_INITIALIZE_OUTPUT(Input, o);
            o.color = _Color * v.color;
        }

        void surf (Input IN, inout SurfaceOutput o)
        {
            fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * IN.color;
            o.Albedo = c.rgb;
            o.Normal = UnpackNormal (tex2D (_NormalsTex, IN.uv_MainTex));
            o.Alpha = c.a;
        }
        ENDCG
    } 
    FallBack "Diffuse"
}
Shader需要的法线贴图可以通过一个软件:PixPlant生成出来,只需提供原素材图,这个软件就能生成一个法线贴图了。

此外还需要一张阴影梯度图:

技术分享

版权声明:本文为博主原创文章,未经博主允许不得转载。

Unity2D实现贴图凹凸感并接受实时光照效果

标签:unity   shader   2d   光影   凹凸   

原文地址:http://blog.csdn.net/leohijack/article/details/46743311

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!