【问题标题】:Unity Vertex Shaders - Gradient color that rotates around the texture's centerUnity Vertex Shaders - 围绕纹理中心旋转的渐变色
【发布时间】:2017-02-19 16:00:41
【问题描述】:

你好,

我正在尝试实现一个围绕中心旋转颜色的渐变着色器,就像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

感谢您的宝贵时间。

【问题讨论】:

    标签: unity3d shader vertex-shader


    【解决方案1】:

    您的代码似乎按预期工作,除了旋转发生在四边形 (0,0) 的 UV 坐标原点周围,该原点位于角落中。考虑到您的 UV 已标准化,您只需在转换前后进行偏移。

    关于 optim 的附注:您可能不需要每帧都从代码中设置矩阵,您可以在着色器中动态创建它,因为您可以访问全局 _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 参数可以是材料常数

    【讨论】:

      猜你喜欢
      • 2018-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多