- Home /
real time vertex shading / color or transparency by vertex height
I have a plane that has many vertices. I have been playing around with a script that deforms the plane by moving the verts up and down (terrain) on run time to deform the plane.
I was wondering if it's possible to change the assigned material's color or transparency by each vertice by its height in run time? With the plane's Y 0 being neutral and transparent or particle/multiply. Then a vertices deviance would add +3 = white -3 = black etc. (imagine snowy peaks and dark troughs.)
Really not good with shaders... any clues welcomed.
Answer by devin8 · Jan 03, 2013 at 10:06 PM
I made this shader for practice.
Shader "Custom/HeightShader" {
Properties {
_MainTex ("Main Texture", 2D) = "white" {}
_CenterHeight ("Center Height", Float) = 0.0
_MaxVariance ("Maximum Variance", Float) = 3.0
_HighColor ("High Color", Color) = (1.0, 1.0, 1.0, 1.0)
_LowColor ("Low Color", Color) = (0.0, 0.0, 0.0, 1.0)
}
SubShader {
Tags { "RenderType"="Opaque" }
Cull Off
CGPROGRAM
#pragma surface surf Lambert vertex:vert
#include <UnityCG.cginc>
float _CenterHeight;
float _MaxVariance;
float4 _HighColor;
float4 _LowColor;
sampler2D _MainTex;
struct Input{
float2 uv_MainTex;
float4 color : COLOR;
};
void vert(inout appdata_full v){
// Convert to world position
float4 worldPos = mul(_Object2World, v.vertex);
float diff = worldPos.y - _CenterHeight;
float cFactor = saturate(diff/(2*_MaxVariance) + 0.5);
//lerp by factor
v.color = lerp(_LowColor, _HighColor, cFactor);
}
void surf(Input IN, inout SurfaceOutput o){
o.Albedo = tex2D(_MainTex, IN.uv_MainTex).rgb * IN.color;
}
ENDCG
}
FallBack "Diffuse"
}
Here's the result..
You can tune a lot of parameters including center height, variance, colors at extremes and also apply a general texture. This shader also interacts with lights.
Cheers
Answer by Piflik · Jul 19, 2012 at 08:03 PM
Not sure how to do this with a shader, but you could probably do this with a simple gradient and some UV operations. (each vertex would get an arbitrary U coordinate, the V coordinate would be the height, normalized, so it is between 0 and 1)
Your answer
![](https://koobas.hobune.stream/wayback/20220613061916im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Vertex Shader problem with _WorldSpaceCameraPos 1 Answer
Painted Vertices are Blockly, Looking to smooth them Out 1 Answer
How can I get the attenuation value of a spotlight in a shader? 0 Answers
Setting and storing vertex locations in a shader 0 Answers
Screen shaders that alter geometry at runtime or through camera 1 Answer