Unity 聚焦物体(Frame Selected)

就是找出 bounds max的一个点,计算与摄像机的距离,然后确定它
https://answers.unity.com/questions/13267/how-can-i-mimic-the-frame-selected-f-camera-move-z.html

Bounds CalculateBounds(GameObject go)
{
     Bounds b = new Bounds(go.transform.position, Vector3.zero);
     UnityEngine.Object[] rList = go.GetComponentsInChildren(typeof(Renderer));
     foreach (Renderer r in rList)
     {
         b.Encapsulate(r.bounds);
     }
     return b;
 }
 public Vector3 FocusCameraOnGameObject(Camera c, GameObject go)
 {
     Bounds b = CalculateBounds(go);
     Vector3 max = b.size;
     // Get the radius of a sphere circumscribing the bounds
     float radius = max.magnitude / 2f;
     // Get the horizontal FOV, since it may be the limiting of the two FOVs to properly encapsulate the objects
     float horizontalFOV = 2f * Mathf.Atan(Mathf.Tan(c.fieldOfView * Mathf.Deg2Rad / 2f) * c.aspect) * Mathf.Rad2Deg;
     // Use the smaller FOV as it limits what would get cut off by the frustum        
     float fov = Mathf.Min(c.fieldOfView, horizontalFOV);
     float dist = radius / (Mathf.Sin(fov * Mathf.Deg2Rad / 2f));
     Debug.Log("Radius = " + radius + " dist = " + dist);
     c.transform.localPosition = new Vector3(c.transform.localPosition.x, c.transform.localPosition.y, -dist);
     if (c.orthographic)
         c.orthographicSize = radius;

     // Frame the object hierarchy
     c.transform.LookAt(b.center);

     var pos = new Vector3(c.transform.localPosition.x, c.transform.localPosition.y, dist);
     return pos;
 }
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值