- Home /
Change vertex colours based on steepness
I'm messing around with generated terrain using some triangles and Perlin Noise, and I was wondering how I would change the colour of the vertices based on the steepness.
My best guess would be to get the angle between the triangle and Vector3.up and then just evaluate that on a gradient for every triangle in the terrain, but I've been having a hard time figuring out how I would actually do that.
Thanks!
Answer by TreyH · Nov 15, 2020 at 02:38 AM
With a triangle, you have 3 points by default -- conveniently enough for a plane, which has a normal vector:
float CalculateSteepnessAngle(Vector3 a, Vector3 b, Vector3 c)
{
// Get 2 vectors from these 3 points, it doesn't matter
// which ones we use as long as they're from the same point
var ab = b - a;
var ac = c - a;
// The cross of those 2 vectors will be the planar normal
var n = Vector3.Cross(ab, ac);
// The angular difference between this normal and the
// world's up vector can be used for a steepness value
return Vector3.Angle(n, Vector3.up);
}
So with that, you should be able to determine "steepness" for a given triangle on your terrain.
Np! I though about it a little more and the decision to cross either AB x AC or AC x AB will change the planar normal direction, giving 2 different values depending on how the triangle ends up composed.
You might need to modify it with something like
var n1 = Vector3.Cross(ab, ac);
var n2 = Vector3.Cross(ac, ab);
var angle1 = Vector3.Angle(n1, Vector3.up);
var angle2 = Vector3.Angle(n2, Vector3.up);
return $$anonymous$$athf.$$anonymous$$in(angle1, angle2);
to account for that, as the smaller angle will probably be what you want.