您的位置:首页 > 移动开发 > Unity3D

Shader学习案例一---屏幕特效之黑白化当前屏幕

2017-06-22 10:54 369 查看
更新:意外发现乐乐女神(《Unity Shader入门精要》的作者)早在csdn中写了很多案例,所以请观众转场吧,比我写的好太多,有清晰的解释,后续相同的不再写了,如果有我自己写的Shader,再贴出来供大家参考。

前言

最近开始研究Unity Shader,学习过程中的一些实操案例记录在此,方便以后查询,并供大家参考。案例中如为书本所述,我会在“来源”中注明书名;如为网上所得,我会注明网址;如为自己所写,简述为原创。

:仅提供案例,不对代码进行详细解读,因为有很多代码我也不知道(毕竟是菜鸟程序员)

来源

书名:Unity 5.x Shaders and Effects Cookbook

目标

将当前屏幕画面黑白化,程度可调节;

过程

一.编写Shader

1. Properties块

_MainTex ("Texture", 2D) = "white" {}
_LuminosityAmount ("GrayScale Amount", Range(0.0,1.0)) = 1.0


_MainTex作为后面C#脚本将用到的srcTexture(我猜的),不要拖拽具体Texture进行赋值,_LuminosityAmount用来控制黑白化程度。

2. SubShader块

SubShader
{
Pass
{
CGPROGRAM
#pragma vertex vert_img
#pragma fragment frag
#pragma fragmentoption ARB_precision_hint_fastest

bbab
#include "UnityCG.cginc"

sampler2D _MainTex;
fixed _LuminosityAmount;

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

float luminosity = 0.299 * renderTex.r + 0.587 * renderTex.g + 0.114 * renderTex.b;

fixed4 col = lerp(renderTex, luminosity,_LuminosityAmount);

return col;
}
ENDCG
}
}


简单说就是对当前屏幕进行采样后,将rgb各值乘以对应的系数值,再通过可控制的_LuminosityAmount值进行插值运算得到最终的颜色。

二、编写C#脚本

直接上代码,最关键的部分是OnRenderImage方法,这个方法是Unity提供的,将该脚本挂载到Camera上即可,Unity会自动调用该方法,不用我们手动调用;

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

[ExecuteInEditMode]
public class TestRenderImage : MonoBehaviour {
public Shader curShader;
[Range(0.0f,1.0f)]
public float grayScaleAmount = 1.0f;
private Material curMaterial;

public Material CurMaterial {
get{
if (curMaterial == null) {
Material mat = new Material (curShader);
mat.hideFlags = HideFlags.HideAndDontSave;
curMaterial = mat;
}
return curMaterial;
}
}
// Use this for initialization
void Start () {
if (!SystemInfo.supportsImageEffects) {
enabled = false;
return;
}
if (!curShader && !curShader.isSupported) {
enabled = false;
}
}

void OnDisable(){
if (curMaterial) {
DestroyImmediate (curMaterial);
}
}

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


三、Unity操作

1.为演示效果,场景中创建一个Sphere,新建一个Material,Shader选择Standard,Albedo的颜色改为红色;

2.将第二步的C#脚本挂载到MainCamera下,并将第一步的Shader赋给变量curShader;

3.因为设定了[ExecuteInEditor],所以不用运行,直接改变grayScaleAmount的值即可看到效果;

结果

grayScaleAmount = 0



grayScaleAmount = 1

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  unity shader