Unity中Shader黑白阀值后处理效果


前言

在上篇文章中,我们讲解了Unity后处理的脚本和Shader。我们在这篇文章中实现一个黑白的后处理Shader


一、我们先来PS看一下黑白阀值的效果

在这里插入图片描述请添加图片描述


二、使用step(a,b)函数实现效果

由PS内效果可得出,使用step函数可以达到类型的效果
在PS内,黑白阀值是值越小越白,而step函数 a<b 才返回1(白色)
所以,我们让 控制变量 为 a ,颜色通道 为 b。实现出一样的效果

fixed4 frag (v2f_img i) : SV_Target
{
	fixed4 col = tex2D(_MainTex, i.uv);

	return step(0.2,col.r);
}

在这里插入图片描述


三、实现脚本控制黑白阀值

1、在Shader属性面板定义控制阀值变量

_Value(“Value”,float) = 0.2

2、把step的a改为_Value

fixed4 frag (v2f_img i) : SV_Target
{
	fixed4 col = tex2D(_MainTex, i.uv);
	return step(_Value,col.r);
}

3、在后处理脚本设置公共成员变量,并且设置范围为(0,1)

[Range(0,1)]public float Value = 0;

4、在Graphics.Blit赋值材质前,给材质的_Value赋值

private void OnRenderImage(RenderTexture source, RenderTexture destination)
{
	Mat.SetFloat("_Value",Value);
	Graphics.Blit(source,destination,Mat);
}

四、最终代码 和 效果

请添加图片描述

Shader:

Shader "Hidden/P2_7_4"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _Value("Value",float) = 0
    }
    SubShader
    {
        // No culling or depth
        Cull Off 
        ZWrite Off 
        ZTest Always

        Pass
        {
            CGPROGRAM
            #pragma vertex vert_img
            #pragma fragment frag

            #include "UnityCG.cginc"
            
            sampler2D _MainTex;

            fixed _Value;
            
            fixed4 frag (v2f_img i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);

                return step(_Value,col.r);
            }
            ENDCG
        }
    }
}

C#:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//后处理脚本
[ExecuteInEditMode]
public class P2_7_3 : MonoBehaviour
{
    [Range(0,1)]public float Value = 0;
    
    public Shader PostProcessingShader;
    
    private Material mat;

    public Material Mat
    {
        get
        {
            if (PostProcessingShader == null)
            {
                Debug.LogError("没有赋予Shader");
                return null;
            }
            if (!PostProcessingShader.isSupported)
            {
                Debug.LogError("当前Shader不支持");
                return null;
            }
            //如果材质没有创建,则根据Shader创建材质,并给成员变量赋值存储
            if (mat == null)
            {
                Material _newMaterial = new Material(PostProcessingShader);
                _newMaterial.hideFlags = HideFlags.HideAndDontSave;
                mat = _newMaterial;
                return _newMaterial;
            }
            return mat;
        }
    }

    private void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        Mat.SetFloat("_Value",Value);
        Graphics.Blit(source,destination,Mat);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_51603875/article/details/134909777
今日推荐