2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Unity]カメラ前平面における画面内サイズを表示する

Last updated at Posted at 2020-02-02

スクリーンショット-2020-02-03-2.05.15.gif

画面のすぐ外から敵を登場させたり、カメラ前数mの表示範囲を知りたい時など、カメラの視錐台表示では大きすぎて位置関係がよくわからないことがあります。

そんなときに便利な、カメラ前平面における表示範囲をRectで返してくれる関数です。

public static Rect GetViewRectOnPlane(Camera _cam, float _dist){
    float w=0f,h=0f;
    if(!_cam.orthographic){
        Vector3[] frustumCorners = new Vector3[4];
        _cam.CalculateFrustumCorners(new Rect(0, 0, 1, 1), -_dist, Camera.MonoOrStereoscopicEye.Mono, frustumCorners);
        h = (frustumCorners[1]-frustumCorners[0]).magnitude*0.5f;
        w = (frustumCorners[2]-frustumCorners[1]).magnitude*0.5f;
    }else{
        h = _cam.orthographicSize;
        w = h*((float)Screen.width/(float)Screen.height);
    }
    return new Rect(0f,0f,w,h);
}

これを使って、OnDrawGizmos()内でカメラ前にRectをデバッグ表示するとわかりやすいかと思います。

float fwd=4f;
Rect rect = GetViewRectOnPlane(camera,fwd);
Vector3 camPos = camera.transform.position;
Vector3 fwdPos = Vector3.forward*fwd;
Vector3 pLT = new Vector3(-rect.size.x,rect.size.y,0f);
Vector3 pRT = new Vector3(rect.size.x,rect.size.y,0f);
Vector3 pLB = new Vector3(-rect.size.x,-rect.size.y,0f);
Vector3 pRB = new Vector3(rect.size.x,-rect.size.y,0f);
fwdPos = camera.transform.rotation * fwdPos;
pLT = camera.transform.rotation * pLT;
pRT = camera.transform.rotation * pRT;
pLB = camera.transform.rotation * pLB;
pRB = camera.transform.rotation * pRB;
Gizmos.DrawLine(camPos+fwdPos+pLT,camPos+fwdPos+pRT);
Gizmos.DrawLine(camPos+fwdPos+pLB,camPos+fwdPos+pRB);
Gizmos.DrawLine(camPos+fwdPos+pLT,camPos+fwdPos+pLB);
Gizmos.DrawLine(camPos+fwdPos+pRT,camPos+fwdPos+pRB);
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?