本文主要是介绍Unity Shader实现等高线,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Unity Shader实现等高线
需求
在做地形时,会遇到显示数字化过程中要有等高线显示的需求
思考实现原理
在Pixel Shader(Unity shder 中为fragment阶段)中通过判断像素点在世界坐标系下的高度值来计算绘制等高线(Unity 中对应时Y值).具体数学转换原理如下图:
具体数学推理
设HeightOffset为U1+U2,HeightLineRate为U2在HeightOffset中所占的百分比,如下Unity Shader中的推理:
fixed tempRate = i.worldPos.y / _HeightOffset;//当前像素高度除HeightOffset
fixed fract = tempRate - floor(tempRate);//取小数部分即得到比例值(fact 在unity shader中不识别所以用这个方法)
fixed funRes =1- step(fract,1 -_HeightLineRate);//算出当前高度是否在U2的比例范围内,是为1,不是为0
具体Shader代码
Shader "Custom/ISOheight等高线"
{Properties{_MainTex ("Texture", 2D) = "white" {}_BaseColor("BaseColor",Color) = (1,1,1,1)_LineColor("LineColor",Color) = (1,1,1,1)_HeightLineRate("HeightLineRate",Range(0,1)) = 1//等高线占HeightOffset的比例_HeightOffset("HeightOffset",Float) = 10//高度分段}SubShader{Tags { "RenderType"="Opaque" }LOD 100Pass{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;float3 worldPos:TEXCOORD1;};sampler2D _MainTex;float4 _MainTex_ST;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 _BaseColor;fixed4 _LineColor;float _HeightOffset;float _HeightLineRate;fixed4 frag (v2f i) : SV_Target{// sample the texturefixed4 col = tex2D(_MainTex, i.uv) * _BaseColor;fixed tempRate = i.worldPos.y / _HeightOffset;//当前像素高度除HeightOffsetfixed fract = tempRate - floor(tempRate);//取小数部分即得到比例值(fact 在unity shader中不识别所以用这个方法)fixed funRes =1- step(fract,1 -_HeightLineRate);//算出当前高度是否在U2的比例范围内,是为1,不是为0fixed4 fincolor = col * (1-funRes) + _LineColor * funRes ;return fincolor;}ENDCG}}
}
效果比对图
理想效果图:
简单实现效果图:
这篇关于Unity Shader实现等高线的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!