美文网首页Unity Shader分享
Unity3D教程宝典之Shader篇:第三讲Vertex&am

Unity3D教程宝典之Shader篇:第三讲Vertex&am

作者: 你的头好大 | 来源:发表于2017-09-28 18:16 被阅读6次

    原文地址:http://blog.sina.com.cn/s/blog_471132920101d5oz.html

    Vertex and Fragment Shader:最强大的Shader类型
    ,也是本系列的重点,下文中简称V&F Shader,属于可编程渲染管线. 使用的是CG/HLSL语法。
    分为2个部分vertex顶点部分和Fragment像素部分。下面依然通过写几个简单的Shader来学习。

    例一:显示一张贴图
    新建Unity工程,新建一个Cube立方体,新建一个名为Exam1的Shader(Project视图->Create->Shader),输入如下代码。

    Shader "Custom/Exam1" {
    Properties {
    _MainTex ("Texture", 2D) = "white" { }
    }
    SubShader
    {
    pass
    {
    CGPROGRAM
    #pragma vertex vert
    #pragma fragment frag
    #include "UnityCG.cginc"
    sampler2D _MainTex;
    float4 _MainTex_ST;
    struct v2f {
        float4  pos : SV_POSITION;
        float2  uv : TEXCOORD0;
    } ;
    v2f vert (appdata_base v)
    {
        v2f o;
       o.pos = mul(UNITY_MATRIX_MVP,v.vertex);
    o.uv = TRANSFORM_TEX(v.texcoord,_MainTex);
        return o;
    }
    float4 frag (v2f i) : COLOR
    {
    float4 texCol = tex2D(_MainTex,i.uv);
        float4 outp = texCol;
        return outp;
    }
    ENDCG
    }
    }
    }
    

    详细讲解如下图
    Shader" action-data="http%3A%2F%2Fs13.sinaimg.cn%2Fmw690%2F47113292gd0b7f9f46efc%26690" action-type="show-slide" style="margin: 0px; padding: 0px; border: 0px; list-style: none;">
    之后我们把之前创建的立方体的shader设置为Exam1,Inspector里有对应的Texture。然后把第三行代码中"Texture" 改为 “Exam 1 texture”,这时回到Inspector面板,你会发现什么?没错贴图的名字提示也相应的改变了。就这么简单,到这你已经学会,将任意贴图赋给任意模型的方法了。
    Shader" action-data="http%3A%2F%2Fs12.sinaimg.cn%2Fbmiddle%2F47113292g7b4591df5b8b%26690" action-type="show-slide" style="margin: 0px; padding: 0px; border: 0px; list-style: none;">
    PS:
    裁剪空间的范围是[-1,1],也就是在经过MVP矩阵后,o.pos.x/ o.pos.w 以及o.pos.y/ o.pos.w 的范围都是[-1,1] 故可以将裁剪空间坐标转换为 相对屏幕位置的uv坐标,如下
    o.uv = float2(( o.pos.x/o.pos.w+1)0.5,(o.pos.y/o.pos.w+1)0.5);

    相关文章

      网友评论

        本文标题:Unity3D教程宝典之Shader篇:第三讲Vertex&am

        本文链接:https://www.haomeiwen.com/subject/ggsvextx.html