Unity Shader unity文档学习笔记(十八):unity雾效原理

看很多文章用近平面远平面组成矩阵后转到裁剪空间下通过Z值来解,实际更简单的方式可以直接通过判断距离来实现

FogMgr控制远近面

复制代码
public class TestFog : MonoBehaviour
{
    public int startDis = 0;
    public int endDis = 50;

    public Vector4 fogParam;

    public void Awake()
    {
        fogParam = new Vector4(startDis, endDis, 0, 0);
        Shader.SetGlobalVector("DisFog", fogParam);
    }
}

Test_Fog.cginc 库

复制代码
#ifndef TEST_FOG
#define TEST_FOG

float4 DisFog;

float MyComputerFog(float3 worldPos)
{
    float fogFactory = distance(worldPos.xz, _WorldSpaceCameraPos.xz)/(DisFog.y - DisFog.x);
    return fogFactory;
}

#endif

TestFog shader

复制代码
Shader "Test/TestFog"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _FogColor ("FogColor", Color) = (1, 1, 1, 1)
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

		    #include "UnityCG.cginc"
            #include "Test_Fog.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
               	float3 worldPos : TEXCOORD1;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;

            float4 _FogColor;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                o.worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                // sample the texture
                fixed4 col = tex2D(_MainTex, i.uv);
                fixed4 fogColor = _FogColor * MyComputerFog(i.worldPos);
                return lerp(col, fogColor, 0.5);
            }
            ENDCG
        }
    }
}

效果

相关推荐
小草帽学编程1 天前
camera功能真的那么难用吗
数码相机·图形渲染
EtpBot-萧阳11 天前
SDL2常用函数:SDL_Texture 数据结构及使用介绍
图形渲染·sdl2·硬件加速
GISer_Jing12 天前
工作流长任务处置方案
前端·编辑器·图形渲染
EtpBot-萧阳12 天前
SDL2常用函数:SDL_BlitSurface&SDL_UpdateWindowSurface 数据结构及使用介绍
算法·ffmpeg·图形渲染·sdl2
冒泡P17 天前
Unity Shader入门(更新中)
unity·c#·游戏引擎·图形渲染·着色器
平和男人杨争争18 天前
山东大学计算机图形学期末复习15——CG15
人工智能·算法·计算机视觉·图形渲染
龙湾开发19 天前
计算机图形学编程(使用OpenGL和C++)(第2版)学习笔记 13.几何着色器(二)爆炸效果&修改图元类型
c++·笔记·学习·3d·图形渲染·着色器
平和男人杨争争19 天前
山东大学计算机图形学期末复习11——CG13上
算法·图形渲染
achonor20 天前
UnityShader 植物被风吹弯效果
unity·shader·mesh
龙湾开发20 天前
计算机图形学编程(使用OpenGL和C++)(第2版)学习笔记 12.曲面细分
c++·笔记·学习·3d·图形渲染