由于人眼對RGB敏剛程度不同,對綠色的敏感度最高,對紅色的敏感度次之,對藍色的敏感度最低,因此需要對RGB設定不同的權重,來達到灰度顯示的效果,比較常用的RGB權重值為 R:0.298912, G:0.586611,B: 0.114478
grayColor.rgb = float3(color.r0.298912 , color.g0.586611 ,color.b*0.114478)
1 UI物件不可用的時候顯示置灰效果
通過shader進行控制置灰,shader中添加變數 _ShowGray,在代碼中可以通過動態給改變數賦值的方式,控制是否進行置灰顯示
shader 代碼是通過 Image Effect shader進行簡單修改得到的,
Shader "UI/UIGray"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
[Toggle]_ShowGray("show gray", Range(0,1)) = 0
}
SubShader
{
// No culling or depth
Cull Off ZWrite Off ZTest Always
//-----add code-------
Blend SrcAlpha OneMinusSrcAlpha
//----finish----
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
sampler2D _MainTex;
fixed _ShowGray;
fixed4 frag (v2f i) : SV_Target
{
fixed4 col = tex2D(_MainTex, i.uv);
// just invert the colors
//col.rgb = 1 - col.rgb;
//----add code----
fixed gray = dot(col.rgb, float3(0.298912, 0.586611, 0.114478));
col.rgb = lerp(col.rgb, fixed3(gray, gray, gray), _ShowGray);
//-----finish-----
return col;
}
ENDCG
}
}
}
2 場景中所有物件置灰,比如戰斗失敗時候顯示的置灰效果
場景置灰,一般采用的是對相機渲染進行設定,在相機上面添加腳本,在OnRenderImage回呼方法里面,對渲染物件進行處理
腳本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PostEffectGray : MonoBehaviour
{
public Material grayMaterial;
void OnRenderImage(RenderTexture src, RenderTexture dest)
{
Graphics.Blit(src, dest, grayMaterial);
}
}
啟用置灰腳本

禁用置灰腳本

這里的Gray材質球用的的shader是一個簡單的置灰效果shader,代碼如下
Shader "Unlit/Gray"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
// make fog work
#pragma multi_compile_fog
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
UNITY_FOG_COORDS(1)
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
float4 _MainTex_ST;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
UNITY_TRANSFER_FOG(o,o.vertex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
// sample the texture
fixed4 col = tex2D(_MainTex, i.uv);
half3 gray = dot(col.rgb, half3 (0.22, 0.707, 0.071));
// apply fog
UNITY_APPLY_FOG(i.fogCoord, col);
return fixed4(gray.rgb, col.a);
}
ENDCG
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/289396.html
標籤:其他
上一篇:2021.7.19模擬賽C組總結
