[Unity] Gradient에서 색등 무늬 생성

5832 단어 Unity
Unity Gradient 클래스의 인스턴스에서 런타임에 색상 램프 텍스쳐를 생성하고 그림자에 사용할 때까지의 방법입니다.
색인에서 Gradient의 점차적인 변화를 설정하고 CreateTexture에서 Gradient에서 무늬를 생성합니다.
텍스쳐는 x 방향으로 그라데이션됩니다.
GradientTextureTest
using UnityEngine;

[ExecuteInEditMode]
public class GradientTextureTest : MonoBehaviour {

    [SerializeField] private Gradient gradient;

    private void Awake()
    {
        Material material = new Material(Shader.Find("Custom/Gradient"));
        material.SetTexture("_GradientTex", CreateTexture());
        GetComponent<Renderer>().material = material;
    }

    private Texture2D CreateTexture()
    {
        Texture2D texture = new Texture2D(128, 1);
        for (int h = 0; h < texture.height; h++)
        {
            for (int w = 0; w < texture.width; w++)
            {
                texture.SetPixel(w, h, gradient.Evaluate((float)w / texture.width));
            }
        }

        texture.Apply();
        texture.wrapMode = TextureWrapMode.Clamp;
        return texture;
    }
}
사용한 면도기.텍스쳐는 수직 및 _Dir에 지정된 방향의 각도에 따라 샘플링됩니다.
Shader "Custom/Gradient"
{
    Properties
    {
        _GradientTex ("Gradient Texture", 2D) = "white" {}
        _Dir ("Direction", Vector) = (0, 1, 0)
    }
    SubShader
    {
        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float3 normal : NORMAL; 
            };

            struct v2f
            {
                float4 vertex : SV_POSITION;
                float3 normal : TEXCOORD0;
            };

            sampler2D _GradientTex;
            float3 _Dir;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.normal = UnityObjectToWorldNormal(v.normal);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                float3 normal = normalize(i.normal);
                float3 dir = normalize(_Dir);
                float3 col = tex2D(_GradientTex, float2(dot(normal, dir) * 0.5+ 0.5, 0));
                return fixed4(col, 1.0);
            }
            ENDCG
        }
    }
}
Sphere 메쉬를 사용하면 이렇게 되는 느낌.

좋은 웹페이지 즐겨찾기