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代码如下:
 
 
 
 
 
 
 
 
posted @ 2016-03-09 13:32  王赛  阅读(3580)  评论(0编辑  收藏  举报