1. 空のオブジェクトを作成し、ボックスという名前を付けます (任意の名前を使用できますが、コードと一致する必要があります)
2. ボックスを選択し、プロパティ パネルで [コンポーネントの追加] をクリックして、ボックス コライダー コンポーネントを追加します。
3. ボックスコライダーのサイズを、制限したい領域のサイズに設定します(私はシーンのサイズに直接設定しました)。
3. 作成したばかりのボックス オブジェクト (選択用) をカメラ スクリプトで変数ボックスを定義します。
public GameObject box;
4. カメラスクリプトに位置を制限する機能を追加
private void limitation()
{
if (box)
{
Vector3 boxSize= box.GetComponent<BoxCollider>().size;
Vector3 boxCenter= box.GetComponent<BoxCollider>().center;
Vector3 min= box.transform.position + boxCenter- boxSize* 0.5f;
Vector3 max= box.transform.position + boxCenter+ boxSize* 0.5f;
Vector3 cameraP = transform.position;
if (cameraP.x < min.x)
{
cameraP.x = min.x;
}
else if (cameraP.x > max.x)
{
cameraP.x = max.x;
}
if (cameraP.y < min.y)
{
cameraP.y = min.y;
}
else if (cameraP.y > max.y)
{
cameraP.y = max.y;
}
if (cameraP.z < min.z)
{
cameraP.z = min.z;
}
else if (cameraP.z > max.z)
{
cameraP.z = max.z;
}
transform.position = cameraP ;
}
}
5. カメラアップデートのUpdate関数に制限機能を配置する
6. スクリプトを保存し、エディターでスクリプトで作成した変数にボックスを追加します。
注: スクリプトはカメラにマウントされています。コードを保存すると、スクリプトに追加のボックス属性 (パブリック ゲームオブジェクト ボックスによって作成されたもの) があることがわかり、シーン内のボックス オブジェクトをそこにドラッグします。
7. カメラを保存して実行した後は、制限エリア内でのみ移動できます。
完全なコード:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cameraHandle : MonoBehaviour
{
public GameObject box;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
limitation();
}
private void limitation()
{
if (box)
{
Vector3 boxSize= box.GetComponent<BoxCollider>().size;
Vector3 boxCenter= box.GetComponent<BoxCollider>().center;
Vector3 min= box.transform.position + boxCenter- boxSize* 0.5f;
Vector3 max= box.transform.position + boxCenter+ boxSize* 0.5f;
Vector3 cameraP = transform.position;
if (cameraP.x < min.x)
{
cameraP.x = min.x;
}
else if (cameraP.x > max.x)
{
cameraP.x = max.x;
}
if (cameraP.y < min.y)
{
cameraP.y = min.y;
}
else if (cameraP.y > max.y)
{
cameraP.y = max.y;
}
if (cameraP.z < min.z)
{
cameraP.z = min.z;
}
else if (cameraP.z > max.z)
{
cameraP.z = max.z;
}
transform.position = cameraP ;
}
}