Determine a radius on terrain and lerp the border to smooth the height flattening

I know it looks like a complex question so here’s what I’m doing. Currently I can determine an area, get the terrain heights in that area, filter the results to fit inside a circle and then set a flat height to those. Which gives me the 2nd result in the image attached. Just a flat height inside a circle.

Question is, how can I smooth the height around that circle so that it looks like number 3? My math check cannot roll high enough for this battle :slight_smile:

float[,] heightsAroundBuilding =
                 _mainTerrainData.GetHeights(terX - radius/2, terZ - radius/2, radius, radius);
            
             float heightScale = 1.0f / _mainTerrainData.size.y;
             for (int i = 0; i < radius; i++)
             {
                 for (int j = 0; j < radius; j++)
                 {
                     float heightToSet = (spawnPosition.y - heightOffset) * heightScale;
                     if ((i - radius / 2) * (i - radius / 2) + (j - radius / 2) * (j - radius / 2) < radius * 2)
                     {
                         //SMOOTHING LOGIC HERE probably via lerp?
                         heightsAroundBuilding[i, j] = heightToSet;
                     }
                 }
             }
_mainTerrainData.SetHeights(terX - radius/2, terZ - radius/2, heightsAroundBuilding);

What you need is a gradient function accepting X,Y that gives you a blending factor (0.0 to 1.0) based on where you are on the circle.

You would use that blending factor to lerp between the original terrain height and the terrain height you want to set at each cell.

I find that black / white / gray Texture2Ds can be an easy source of this sort of filter.

You could also do it as a linear gradient, such as with an AnimationCurve, then look up into it based on the distance from center of your mound.

I’ve done the 2D texture approach a bunch of times, let me see if I can find an example. I think the above description should be enough to get you going though.

EDIT: Oh look at that, I already had it extracted to a .unitypackage. Give the attached a whirl. This one not only blends the terrain heightmap smoothly but it also tries to blend the alpha splatmap… it may blow up if you don’t have certain splatmaps enabled, but you should easily be able to carve away unwanted chunks of the code, as it is super top-down Fisher Price coding style.

8182487–1065854–GenerateMountainsWithFlatSpots.unitypackage (2.49 MB)

Hey thanks a TON for going through this! I’ve also already done it by using a gradient texture for this. Somewhat different tho, I resize the texture to the width/length of the Heights array I get, and then just go through pixel by pixel to match the height. Easier for my game.

But regardless, I went through with your package too. Marvelous work. Thanks a lot :slight_smile:

1 Like