実現したいこと
Transform.RotateAroundを用いて、3Dのオブジェクトを中心としてカメラを移動させるプログラムを書いているのですが、オブジェクトの下側が見えないよう(カメラのY座標が0未満にならないよう)に、回転に制限を掛けたいです。
つまりは、水平方向への回転(Y軸回転)は制限なし、かつ垂直方向への回転(X軸・Z軸回転)は0~180度に制限したいです。
また、そのほかの条件は、
・カメラはオブジェクトを常に見続ける
・カメラはスワイプ/ドラッグによって移動・回転する
環境は Unity2022.3.20f1です。
参考にした質問です > https://teratail.com/questions/143996
該当のソースコード
C#
1 Vector3 target; // 回転の中心 2 3 [SerializeField] float sensitivity; // ドラッグの感度 4 Vector2 sPos; // タッチした座標 5 float wid, hei; // スクリーンサイズ 6 float tx, ty; 7 float angleTB, angleLR; // 上下・左右の回転角度 8 9void Start() 10 { 11 wid = Screen.width; 12 hei = Screen.height; 13 } 14 15void Update() 16 { 17 if (Input.touchCount == 1) 18 { 19 Touch t1 = Input.GetTouch(0); 20 if (t1.phase == TouchPhase.Began) 21 { 22 sPos = t1.position; 23 } 24 else if (t1.phase == TouchPhase.Moved) 25 { 26 tx = (t1.position.x - sPos.x) / wid; //横移動量(-1<tx<1) 27 ty = (t1.position.y - sPos.y) / hei; //縦移動量(-1<ty<1) 28 29 // マウス移動量から求めた回転角度 30 float deltaAngleLR = tx * sensitivity; 31 float deltaAngleTB = -ty * sensitivity; 32 33 // 回転の総量 34 angleLR += deltaAngleLR; 35 angleTB += deltaAngleTB; 36 37 // 回転の総量を制限 38 float clampedAngleLR = Mathf.Clamp(angleLR, 0, 180); 39 float clampedAngleTB = Mathf.Clamp(angleTB, 0, 180); 40 41 // 制限値からどれだけ越えたか 42 float overshootLR = angleLR - clampedAngleLR; 43 float overshootTB = angleTB - clampedAngleTB; 44 45 // 角度差分だけ回転量を調整して、制限を超えないように 46 deltaAngleLR -= overshootLR; 47 deltaAngleTB -= overshootTB; 48 angleLR = clampedAngleLR; 49 angleTB = clampedAngleTB; 50 51 transform.RotateAround(target, transform.up, deltaAngleLR); //左右方向 z軸中心の回転 52 transform.RotateAround(target, transform.right, deltaAngleTB); // 上下方向 x軸中心の回転 53 } 54 } 55 }

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。