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
        }
    }
}

效果

相关推荐
BoBoZz1915 小时前
TextureCutQuadric 利用3D隐式函数(Quadrics)来生成2D纹理坐标
python·vtk·图形渲染·图形处理
明洞日记2 天前
【ITK手册001】ITK 架构核心:itk::Object 基类解析与应用指南
c++·图像处理·架构·图形渲染·itk
梵尔纳多2 天前
OpenGL 坐标映射
c++·图形渲染
BoBoZz192 天前
VTKWithNumpy使用 NumPy 数组来创建3D体渲染所需要的数据
python·vtk·图形渲染·图形处理
梵尔纳多3 天前
绘制一个三角形
c++·图形渲染·opengl
明洞日记3 天前
【VTK手册032】vtkImageConstantPad:医学图像边界填充与尺寸对齐
c++·图像处理·vtk·图形渲染
郝学胜-神的一滴3 天前
OpenGL纹理技术详解:从原理到实践
c++·程序人生·游戏程序·图形渲染·贴图
BoBoZz194 天前
RescaleReverseLUT 演示和比较颜色查找表的重标定和反转
python·vtk·图形渲染·图形处理
Huanzhi_Lin5 天前
图形渲染管线流程笔记
笔记·图形渲染·shader·glsl
梵尔纳多6 天前
初识 OpenGL
c++·图形渲染