Unity高度图形成

unity高度图形成主要的原理是对原始模型mesh先形成boundingBox,并在原始模型的上方添加射线方向向下进行碰撞检测,通过碰撞点与射线的截距获得模型的高度值,最后把高度值转换成像素点写入图片中形成最后的高度图

1.先形成boundingBox并获取相关坐标轴的最大值、最小值

    Bounds boundingBox = mesh.bounds;//创建boundingBox  
    float minX = boundingBox.min.x;  
    float minZ = boundingBox.min.z;  
    float maxX = boundingBox.max.x;  
    float maxZ = boundingBox.max.z;  
    float minY = boundingBox.min.y;  
    float maxY = boundingBox.max.y;

2.计算模型宽度和模型高度并设置射线间的宽度和高度

  float widthSize = maxX - minX;  
  float heightSize = maxZ - minZ;

  float cellWidth = widthSize / (width - 1);//单元宽度  
  float cellHeight  = heightSize / (height - 1);//单元高度

3.产生射线并设置方向与起始位置

private static Ray ray = new Ray(new Vector3(), new Vector3());//创建一条射线

Vector3 rayDirE = ray.direction;//设置原始的方向
rayDirE.x = 0;
rayDirE.y = -1;
rayDirE.z = 0;
const float heightOffset =1f;
Vector3 originRay = ray.origin;
float rayY = maxY + heightOffset;//增加Y方向的高度
originRay.y = rayY;
ray.direction = new Vector3(rayDirE.x, rayDirE.y, rayDirE.z);

4.通过碰撞检测得到高度值

   private static float getPosition(Vector3 rayOrigin,Vector3 rayDirection)  
  {  
    float closestIntersection = float.MaxValue;  
    RaycastHit hit;  
    //Debug.DrawLine(rayOrigin, rayOrigin + new Vector3(0, -1, 0) * 100, Color.red, 1000000f);  
    if (Physics.Raycast(rayOrigin, rayDirection, out hit, 10))  
    {  
        float intersection = hit.distance;  
        if ((intersection != 0.0f) && intersection < closestIntersection)  
        {  
            closestIntersection = intersection;  
        }  
    }  
    return closestIntersection;  
}



5.通过得到的高度转化成像素点

     float oriHeight = heightMap. getHeight( i, j);//得到高度  
           // Debug. Log("orheight:" + oriHeight);

            if ( oriHeight == 0. 0f)  
            {  
               color.r = 1;  
               color.g = 1;  
               color.b = 1;  
            }  
            else  
            {  
               double h =(oriHeight - minHeight) / compressionRatio / 255;  
               float y = Convert.ToSingle(h);  
               color.r = y ;  
               color.g = y ;  
               color.b = y ;  
            }

      color. a = 1;

      hMap. SetPixel( height - 1 - j, width - 1 - i, color);

6.把像素点写入到png图片上

    byte[] bytes = hMap.EncodeToPNG();  
    string strFile = Application.dataPath + "/heightMap.png";  
    FileStream file = File.Open(strFile, FileMode.Create);  
    BinaryWriter writer = new BinaryWriter(file);  
    writer.Write(bytes);  
    file.Close();

比如原始图片为


通过以上方法形成高度图:



猜你喜欢

转载自blog.csdn.net/qq_35307209/article/details/80682076
今日推荐