2017-02-19 41 views
0

Heyas有旋转,统一顶点着色器 - 渐变色,围绕纹理的中心

我想实现一个渐变着色器绕中央的颜色,就像这一项上shadertoy,但是这一个是一个片段着色器

这是我第一次使用着色器,现在我已经学习了两天了,但是我很难翻译和习惯线性代数中的许多术语,而且我还没有碰到它因为本地口语课学习。

所以我有旋转矩阵,我通过一个脚本:

public class RotationMatrix : MonoBehaviour 
{ 
    public float rotationSpeed = 10f; 
    public Vector2 texPivot = new Vector2(0.5f, 0.5f); 
    Renderer _renderer; 

    void Start() 
    { 
     _renderer = GetComponent<Renderer>(); 
    } 

    protected void Update() 
    { 
     Matrix4x4 t = Matrix4x4.TRS(-texPivot, Quaternion.identity, Vector3.one); 

     Quaternion rotation = Quaternion.Euler(0, 0, Time.time * rotationSpeed); 
     Matrix4x4 r = Matrix4x4.TRS(Vector3.zero, rotation, Vector3.one); 

     Matrix4x4 tInv = Matrix4x4.TRS(texPivot, Quaternion.identity, Vector3.one); 
     _renderer.material.SetMatrix("_Rotation", tInv * r * t); 
    } 
} 

在这种旋转这样的顶点着色器:

#pragma vertex vert 
#pragma fragment frag 
#include "UnityCG.cginc" 

    sampler2D _MainTex; 
    float4 _MainTex_ST; 
    fixed4 _Color; 
    fixed4 _Color2; 
    fixed _Scale; 
    float4x4 _Rotation; 

    struct v2f { 
     float4 pos : SV_POSITION; 
     fixed4 color : COLOR; 
     float2 uv : TEXCOORD0; 
    }; 

    v2f vert(appdata_full v) 
    { 
     v2f o; 
     o.uv = TRANSFORM_TEX(v.texcoord, _MainTex); 
     v.texcoord.xy = mul(_Rotation, v.texcoord.xy); 
     o.pos = mul(UNITY_MATRIX_MVP, v.vertex); 
     o.color = lerp(_Color, _Color2, v.texcoord.x * _Scale); 

     return o; 
    } 

    fixed4 frag(v2f i) : SV_Target 
    { 
     float4 color; 
     color.rgb = i.color.rgb; 
     color.a = tex2D(_MainTex, i.uv).a * i.color.a; 
     return color; 
    } 


     ENDCG 
    } 
    } 

注意,这真是一个怪人的代码,我从教程和论坛帖子开始构建,因为Cg/HLSL中的所有内容都是新的。

这里是我所得到的:Sorry for the eye cancer

感谢您的时间。

回答

1

看起来你的代码和预期一样工作,只不过旋转发生在四角(0,0)的UV坐标原点附近,而原点位于角落。考虑到你的UV是正常化的,你只需要在转换前后的偏移量为

有关优化的注意事项:您可能不需要在每帧中都从代码中设置矩阵,您可以在着色器中随时创建它,因为您可以访问全局_Time参数。

half2 Rotate2D(half2 _in, half _angle) { 
    half s, c; 
    sincos(_angle, s, c); 
    float2x2 rot = { c, s, -s, c }; 
    return mul(rot, _in); 
} 

因而你rotationSpeed参数可以是材料常数