Unity - 计算 horizontal fov(水平方向上的 field of view)
Unity版本
Unity 2017.4.2
Unity fov
1. 通过Camera组件获取fov(这是vertical fov):
void Start() { Camera mainCamera = Camera.main; float fov = mainCamera.fieldOfView; Debug.Log("fov:" + fov); }
2. 计算horizontal fov
void Start() { Camera mainCamera = Camera.main; float fov = mainCamera.fieldOfView; Debug.Log("fov:" + fov); float fovInRads = fov * Mathf.Deg2Rad; float horizontalFovInRads = 2 * Mathf.Atan(Mathf.Tan(fovInRads / 2) * mainCamera.aspect); float horizontalFov = horizontalFovInRads * Mathf.Rad2Deg; Debug.Log("horizontal fov:" + horizontalFov); }
horizontal fov应用举例
1. 用一张图像作为背景,效果如下:
在Main Camera下创建BackgroundQuad,localPosition=(0, 0, 100),localScale=(100, 100, 1)
2. 我们希望背景图像在水平方向上填满,同时保持原图宽高比,效果如下
Sample Code:
public class bg : MonoBehaviour { public Texture bgTexture; public Transform backgroundQuad; float CalcHorizontalFov() { float fovInRads = Camera.main.fieldOfView * Mathf.Deg2Rad; float horizontalFovInRads = 2 * Mathf.Atan(Mathf.Tan(fovInRads / 2) * Camera.main.aspect); return horizontalFovInRads * Mathf.Rad2Deg; } // Use this for initialization void Start() { float d = 100; // distance form camera to background quad float horizontalFov = CalcHorizontalFov(); float scaleX = Mathf.Tan(horizontalFov * Mathf.Deg2Rad / 2) * d * 2; float scaleY = scaleX * bgTexture.height / bgTexture.width; backgroundQuad.localPosition = new Vector3(0, 0, d); backgroundQuad.localScale = new Vector3(scaleX, scaleY, 1); } }