Hey! I’ve been attempting to calculate the vertex normals in a shader due to the mesh being dynamic. I figured I could do this by grabbing 4 heightmap colour offsets and cross product/ averaging them, but this is giving me just a single normal direction over the entire mesh.
Here is my shader code :
void vert (inout appdata_full v) {
// VERTEX NORMALS START
float2 v1UVs = v.texcoord;
v1UVs.y -= 0.001;
float2 v3UVs = v.texcoord;
v3UVs.y += 0.001;
float2 v4UVs = v.texcoord;
v4UVs.x -= 0.001;
float2 v2UVs = v.texcoord;
v2UVs.x += 0.001;
float4 heightMapv1 = tex2Dlod (_HeightMap, float4(v1UVs,0,0));
float4 heightMapv2 = tex2Dlod (_HeightMap, float4(v2UVs,0,0));
float4 heightMapv3 = tex2Dlod (_HeightMap, float4(v3UVs,0,0));
float4 heightMapv4 = tex2Dlod (_HeightMap, float4(v4UVs,0,0));
float heightv1 = ((heightMapv1.r - 0.5) *2) * 10;
float heightv2 = ((heightMapv2.r - 0.5) *2) * 10;
float heightv3 = ((heightMapv3.r - 0.5) *2) * 10;
float heightv4 = ((heightMapv4.r - 0.5) *2) * 10;
float3 vectorv1 = (0,heightv1,1);
float3 vectorv2 = (1,heightv2,0);
float3 vectorv3 = (0,heightv3,-1);
float3 vectorv4 = (-1,heightv4,0);
float3 crossv12 = normalize(cross(vectorv1, vectorv2));
float3 crossv23 = normalize(cross(vectorv1, vectorv4));
float3 crossv34 = normalize(cross(vectorv3, vectorv4));
float3 crossv41 = normalize(cross(vectorv3, vectorv2));
float3 average12 = normalize((crossv12 + crossv23) * 0.5);
float3 average34 = normalize((crossv34 + crossv41) * 0.5);
float3 average = normalize((average12 + average34) * 0.5);
v.normal = average;
//VERTEX NORMALS END
float4 heightMap = tex2Dlod (_HeightMap, float4(v.texcoord.xy,0,0));
v.vertex.y += ((heightMap.r - 0.5) *2) * 10;
}
I do get some strange warnings on the shader too :
implicit truncation of vector type, comma expression used where a vector constructor may have been intended, potentially unintended use of a comma expression in a variable initializer, floating point division by zero.
Sorry to duplicate this from answers, but I have had no help before on more complex issues ![]()
Thanks!
