鸟语天空
屏幕特效——灰度处理
post by:追风剑情 2016-7-16 14:06

示例:屏幕后期处理——灰度处理

GrayImageShader.Shader

Shader "Custom/GrayImageShader" {
	Properties {
		_MainTex ("Base (RGB)", 2D) = "white" {}
		_LuminosityAmount ("GrayScale Amount", Range(0.0, 1)) = 1.0
	}
	SubShader {
		Pass
		{
			//使用纯CG代码,而不是Unity内置的表面着色器语言。
			//这能使我们屏幕特效更加优化。
			CGPROGRAM
			#pragma vertex vert_img
			#pragma fragment frag
			#pragma fragmentoption ARB_precision_hint_fastest
			#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"
}

TestRenderImage.cs

using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class TestRenderImage : MonoBehaviour {

	public Shader curShader;
	public float grayScaleAmount = 1.0f;
	private Material curMaterial;

	Material material
	{
		get
		{
			if(curMaterial == null)
			{
				curMaterial = new Material(curShader);
				curMaterial.hideFlags = HideFlags.HideAndDontSave;
			}
			return curMaterial;
		}
	}

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

		if(null != curShader && !curShader.isSupported)
		{
			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 Update () {
		grayScaleAmount = Mathf.Clamp (grayScaleAmount, 0.0f, 1.0f);
	}

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

将TestRenderImage挂在主摄像机上

44444.jpg


编辑器中效果截图

grayScaleAmount = 0

1111111.jpg

grayScaleAmount = 0.5

222222222222.jpg

grayScaleAmount = 1

3333333.jpg

评论:
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容