Make objects stick to the ground

This is a 2D representation of 3 situations of buildings placed on terrain(3D):

First is what is currently doing this:
Building.transform.position = new Vecotr3(Building.transform.position.x, terrainRef.SmapleHeight(Building.transform.position), Building.transform.position.z);

The pivot(yellow dot) is on the ground but the edges are floating and some are under terrain.

In the 2nd and 3rd are what I need.

If I want to place the building over a pit, the rotation should be calculated by the angle between 2 sample height of the 2 ends of the buildings. If I want to place it over a mound, the rotation should be calculated by the angle of 2 points that are very approached to the pivot.

For the middle picture, you can only reliably place a tripod on terrain, ie., sample three different heights near the edges of your building, and get a normal from that, and align the building to that normal.

If you emplace all four corners, there might not be an unambiguous solution.

For the right picture, you need still some way to obtain a tangent, which will also require three points for exactly the same reason. You would just sample the terrain very close around your yellow dot to get that approximate tangent.

So a 4-foot chair can only sits on a flat surface. I need to calculate only 3 samples. And after I have 3 points on terrain how to calculate the euler angles for the rotation of the building. w

How to “align the building to that normal”?

Three points can give you a normal (google how; hint: cross product).

Using that normal you can make a Quaternion (perhaps using Quaternion.FromToRotation() ?) to align your objects “up” axis to the normal axis.

Undefined of course is the heading, since you can place an object facing any direction.

Thank you. Now I can imagine this in my head.
And one question: The purple/indigo texture that I found that’s called “Normal Map” is related to the normal vectors? I noticed that normal maps make my materials 3D somehow

Yes… it is a color-encoded “what is the surface tilt at this point” in the same way that an albedo map is “what is the color at this point.”

Much like the color affects how the light is reflected to the camera, this affects the angle at which the light is perceived to have hit the surface. The surface is still completely flat however.

The encoding is something like the red channel tells tilt in the local U axis and the blue channel tells tilt in the local V axis, but I think that is technically not quite correct. I remember reading a wiki article about it…

Thank you. I’ll search more about graphics, shaders…