Unity3D ----- 代碼控制shader的自發光參數(攝像機黑白特效下)


這兩天研究了下shader的一些屬性,做了個黑白特效攝像機下投影的cube的demo。
 
1.設置攝像機
首先攝像機上特效可以通過導入unity自帶的特效包Grayscale腳本掛載到攝像機上來實現,也可自己寫腳本設置。
導入的路徑:Assets—Import Package — Effects。
我沒有導包,自己寫的:
 
// 編輯模式下運行
[ExecuteInEditMode]
public class CameraEffect : MonoBehaviour
{
    #region Variables
    public Shader curShader;
    [Range(-1.0f,1.0f)]
    public float grayScaleAmount = 1.0f;
    private Material curMaterial;
    #endregion
    
    #region Properties
    public Material material 
    {
        get {
            if (curMaterial == null) 
            {
                curMaterial = new Material(curShader);
                curMaterial.hideFlags = HideFlags.HideAndDontSave;
            }
            return curMaterial;
        }
    }
    #endregion

    void Start () 
    {
        if (SystemInfo.supportsImageEffects == false) 
        {
            enabled = false;
            return;
        }
        
        if (curShader != null && curShader.isSupported == false) 
        {
            enabled = false;
        }
    }

    void OnRenderImage (RenderTexture sourceTexture, RenderTexture destTexture)
    {
        if (curShader != null) 
        {
            material.SetFloat("_LuminosityAmount", grayScaleAmount);
            Graphics.Blit(sourceTexture, destTexture, material);
        } else {
            Graphics.Blit(sourceTexture, destTexture);
        }
    }

    // 便於回收
    void OnDisable () 
    {
        if (curMaterial != null) 
        {
            DestroyImmediate(curMaterial);
        }
    }
}

 

 
2.攝像機Shader
自己寫就需要自己寫個shader,這個shader就是設置顏色為黑白灰色
 
代碼:
Shader "Custom/ShaderCamera" {
    Properties {
        _MainTex ("Base (RGB)", 2D) = "white" {}
        _LuminosityAmount ("GrayScale Amount", Range(0.0, 1.0)) = 1.0
    }
    SubShader {
        Pass {
            CGPROGRAM
            #pragma vertex vert_img
            #pragma fragment frag
            
            #include "UnityCG.cginc"
            
            uniform sampler2D _MainTex;
            fixed _LuminosityAmount;
            
            fixed4 frag(v2f_img i) : COLOR
            {
                fixed4 renderTex = tex2D(_MainTex, i.uv);
                
                float luminosity = 0.299 * renderTex.r + 0.587 * renderTex.g + 0.114 * renderTex.b;
                fixed4 finalColor = lerp(renderTex, luminosity, _LuminosityAmount);
                
                return finalColor;
            }
            
            ENDCG
        }
    }
    FallBack "Diffuse"
}

 

 
 
3.設置cube的材質shader
 
給cube附一個材質,自己編寫shader,主要通過改變“Emission”屬性的參數值來調節自發光的顏色。
cube的shader代碼如下:
 
 
 
 
 
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM