前提・実現したいこと
使っているソフト・バ-ジョン unity2017 4.6.11f (最新の安定板)
実現したいこと Unity3Dで複数のオブジェクトが画面内に収まるようにカメラを動かしたい
(左側の図のようにしたい)
試したこと
ネットで調べたやつを試したり(右の図のようになった)
WorldToViewportPointで何とかしようとしたり(うまいこといかなかった)↓
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class 自機位置取得 : MonoBehaviour 6{ 7 public List<Transform> transList = new List<Transform>(); 8 [SerializeField] Camera cam; 9 public float dis; 10 public float diameter; 11 public float margin = 2.0f; 12 public Vector3 posMax; 13 public Vector3 posMin; 14 public Vector3 average; 15 public Transform cameraPos; 16 17 void Start() 18 { 19 cameraPos = GameObject.Find("CameraPosition").GetComponent<Transform>(); 20 } 21 22 void FixedUpdate() 23 { 24 dis = 0f; 25 posMax = new Vector3(0f,0f,1f); 26 posMin = new Vector3(1f,1f,1f); 27 28 foreach (Transform trans in transList) 29 { 30 var a = cam.WorldToViewportPoint(trans.position); 31 dis += Vector3.Distance(cameraPos.transform.position, trans.position); 32 33 if (posMax.x < a.x) 34 { 35 posMax.x = a.x; 36 } 37 if (posMin.x > a.x) 38 { 39 posMin.x = a.x; 40 } 41 if (posMax.y < a.y) 42 { 43 posMax.y = a.y; 44 } 45 if (posMin.y > a.y) 46 { 47 posMin.y = a.y; 48 } 49 } 50 dis = dis / transList.Count; 51 average = (posMax + posMin) * 0.5f; 52 diameter = Vector3.Distance(posMax, posMin) * dis; 53 this.transform.position = this.transform.position 54 + new Vector3((average.x - 0.5f) * dis,(average.y - 0.5f) * dis,dis); 55 cameraPos.position = new Vector3(0f, 1f, -1.5f).normalized * GetCameraDistance(cam, diameter); 56 cameraPos.LookAt(this.transform); 57 } 58 59 public float GetCameraDistance(Camera camera, float height) 60 { 61 if (camera == null || height <= 0.0f) 62 { 63 return 0.0f; 64 } 65 66 float frustumWidth = height / camera.aspect; 67 return frustumWidth + margin / Mathf.Tan(camera.fieldOfView * 0.5f * Mathf.Deg2Rad); 68 } 69}
補足情報
質問しているのは中学生(国語苦手)なので文法のおかしいところが多々あると思います。
見づらかったらごめんなさい。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/09/26 07:45