【Unity】LODGroup calculation formula

        When Unity configures LodGroup, its hierarchical switching calculation method is based on the proportion of the object occupying the camera's field of view. At runtime, if the camera's field of view (Field of View) does not change, then this value can be directly converted into the distance of the object from the camera. Here we discuss how to calculate this distance.

1. Principle of LODGroup switching judgment

        The rendering part will be skipped. Here we will only talk about the principle of Unity’s calculation of Lod switching determination, as shown in the following figure:

        The green area is the field of view, and the blue GameObject is the target object. The value calculated by Unity is the ratio of the size of the GameObject to the current camera field of view, that is, Size / ViewDistance, and uses this as the standard to switch LOD.

        We can configure the grading ratio in LOD Group:


        Taking the above figure as an example, when the Object Size proportion is less than 49.97%, it switches to Lod1, when it is less than 22.8%, it switches to Lod2, and so on.

        This is the case when the object's scaling is 1. The impact of the object's scaling on the screen ratio must also be considered in actual calculations.

2. Calculation method

        Obviously, when the Field of Veiw of the camera remains unchanged, this ratio can be directly converted into the distance of the object from the camera for simple calculation (Camera Distance). Under normal circumstances, in order to save performance, LOD cropping is performed by determining the distance from the camera to the object.

        The calculation principle is a simple trigonometric function. The code is as follows:

Mesh mesh;//自行获取网格
LODGroup group;//自行获取LOD Group
LOD[] lods = group.GetLODs();

//这里是按scale为1算的,实际计算要侧乘上缩放值
float3 size = mesh.bounds.size;

//unity 是取最大值,而不是对角线长度
float objectSize= math.max(math.max(size.x, size.y), size.z);

//根据相机的配置获取相机角度(弧度制)
float cameraAngle = math.radians(CameraFieldOfView * 0.5f);
//计算当物体刚好所占屏幕比例为 1 时,距离相机的距离;
float cameraRatio = objectSize* 0.5f / math.tan(cameraAngle);

//根据相似三角形原理和 LOD Group 配置,分别计算出多级lod物体距离相机的距离
if (lods.Length > 0)
    x = cameraRatio / lods[0].screenRelativeTransitionHeight;
if (lods.Length > 1)
    y = cameraRatio / lods[1].screenRelativeTransitionHeight;
if (lods.Length > 2)
    z = cameraRatio / lods[2].screenRelativeTransitionHeight;
if (lods.Length > 3)
    w = cameraRatio / lods[3].screenRelativeTransitionHeight;

        The lod after the calculation is completed can be saved, and there is no need to calculate it again as long as the camera remains unchanged.

Guess you like

Origin blog.csdn.net/cyf649669121/article/details/133308591