限制功能原著地址:unity限制相机可移动区域(box collider)_unity限制相机移动区域_manson-liao的博客-CSDN博客
一、创建限制区域
创建一个Cube,Scale大小=1,添加组件:BoxCollder,调整BoxCollder的Size(此为限制区域)
二、代码(功能:WADS(或者上下左右方向键)以及使用Q E上升下降移动和鼠标等控制相机的移动转向等,限制功能是类里的方法为:limitation(),放在Update里执行即可)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
namespace Twq
{/// <summary>/// wasd控制 (使用中)/// </summary>public class CameraController03 : MonoBehaviour{public static CameraController03 Instance;[Header("模型")]public Transform targetmodel;public static Transform target;[Header("鼠标滚轮灵敏度")][SerializeField]private int MouseWheelSensitivity = 2;[Header("最近距离")][SerializeField]public int MouseZoomMin = 750;[Header("最远距离")][SerializeField]public int MouseZoomMax = 2000;[Header("水平旋转速度")][SerializeField]private float xSpeed = 150.0f;[Header("竖直旋转速度")][SerializeField]private float ySpeed = 80.0f;[Header("鼠标移动灵敏度")][SerializeField]private float mouseMoveSensitivity = 3.0f;[Header("角度限制")][SerializeField]private int yMinLimit = 0;[SerializeField]private int yMaxLimit = 89;[Header("摄像机初始角度")][SerializeField]private float xRot = 0;[SerializeField]private float yRot = 0;[Header("摄像机位置")][SerializeField]private Vector3 camPos;//= new Vector3(0, 0, 0);public float normalDistance;//初始摄像机距离,无法在面板显示public static float x;//= 69f;public static float y;// 34.2f;private Quaternion rotation;public static Vector3 CameraTarget;// [HideInInspector]public bool isExit;//打开 控制相机public bool isShuBiao;//Flase=拉近 状态public Transform SelfTransform;private void Awake(){Instance = this;SelfTransform = this.transform;}void Start(){//初始化isExit = true;isShuBiao = true;x = yRot;y = xRot;target = targetmodel;Vector3 posC = camPos - target.position;normalDistance = Mathf.Sqrt(Mathf.Pow(posC.x, 2) + Mathf.Pow(posC.y, 2) + Mathf.Pow(posC.z, 2));rotation = Quaternion.Euler(new Vector3(y, x, 0f));transform.rotation = rotation;float z = target.transform.position.z - normalDistance;transform.position = camPos;//rotation * new Vector3(transform.position.x, transform.position.y, z);CameraTarget = transform.position + transform.forward.normalized * normalDistance;x = transform.localEulerAngles.x;y = transform.localEulerAngles.y;}public void Init(){isExit = true;isShuBiao = true;Vector3 posC = camPos - target.position;normalDistance = Mathf.Sqrt(Mathf.Pow(posC.x, 2) + Mathf.Pow(posC.y, 2) + Mathf.Pow(posC.z, 2));rotation = Quaternion.Euler(new Vector3(90f, 0f, 0f));transform.rotation = rotation;transform.position = new Vector3(0f, 0f, 0f);CameraTarget = transform.position + transform.forward.normalized * normalDistance;x = transform.localEulerAngles.x;y = transform.localEulerAngles.y;}public float movespeed = 500;void LateUpdate(){if (IsPointerOverGameObject(Input.mousePosition))if (isExit){if (isShuBiao){// 定义3个值控制移动float xm = 0, zm = 0;if (Input.GetKey(KeyCode.Q)) //上升{if (transform.position.y >= MouseZoomMax)//限制 最大距离{transform.position = new Vector3(transform.position.x, MouseZoomMax, transform.position.z);}else{transform.position = new Vector3(transform.position.x, transform.position.y +movespeed * Time.deltaTime, transform.position.z);}}else if ( Input.GetKey(KeyCode.E))//下降{if (transform.position.y <= MouseZoomMin)//限制 最小距离{transform.position = new Vector3(transform.position.x, MouseZoomMin, transform.position.z);}else{transform.position = new Vector3(transform.position.x, transform.position.y - movespeed * Time.deltaTime, transform.position.z);}}//按键盘W向上移动if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W)){if (transform.position.y < MouseZoomMin)//限制 最小距离{transform.position = new Vector3(transform.position.x, MouseZoomMin, transform.position.z);}else{this.transform.Translate(Vector3.forward * movespeed * Time.deltaTime);}}else if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S))//按键盘S向下移动{if (transform.position.y > MouseZoomMax)//限制 最大距离{transform.position = new Vector3(transform.position.x, MouseZoomMax, transform.position.z);}else{this.transform.Translate(Vector3.back * movespeed * Time.deltaTime);}}if (Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A))//按键盘A向左移动{// xm -= 500 * Time.deltaTime;this.transform.Translate(Vector3.left * movespeed * Time.deltaTime);}else if (Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D))//按键盘D向右移动{// xm += 500 * Time.deltaTime;this.transform.Translate(Vector3.right * movespeed * Time.deltaTime);}if (Input.GetMouseButton(GlobalVariableManage.GetMouseButtonType))// 1鼠标右键 0鼠标左键{y += Input.GetAxis("Mouse X") * xSpeed * 0.02f;x -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;x = ClampAngle(x, yMinLimit, yMaxLimit);var rotation = Quaternion.Euler(x, y, 0);transform.rotation = rotation;}else if (Input.GetAxis("Mouse ScrollWheel") != 0)//鼠标滚轮{// normalized = (transform.position - CameraTarget).normalized;if (normalDistance >= MouseZoomMin && normalDistance <= MouseZoomMax){this.transform.position += this.transform.forward * Input.GetAxisRaw("Mouse ScrollWheel") * Time.timeScale * MouseWheelSensitivity;Vector3 p = this.transform.position - CameraTarget;normalDistance = Mathf.Sqrt(Mathf.Pow(p.x, 2) + Mathf.Pow(p.y, 2) + Mathf.Pow(p.z, 2));}if (normalDistance < MouseZoomMin){normalDistance = MouseZoomMin;}if (normalDistance > MouseZoomMax){normalDistance = MouseZoomMax;}if (transform.position.y < MouseZoomMin)//限制 最小距离{transform.position = new Vector3(transform.position.x, MouseZoomMin, transform.position.z);}if (transform.position.y > MouseZoomMax)//限制 最大距离{transform.position = new Vector3(transform.position.x, MouseZoomMax, transform.position.z);}}}else{if (transform.position.y > MouseZoomMax)//限制 最小距离{isShuBiao = true;}//缩放if (Input.GetAxis("Mouse ScrollWheel") > 0){transform.Translate(Vector3.forward * 100f);//速度可调 自行调整}if (Input.GetAxis("Mouse ScrollWheel") < 0){transform.Translate(Vector3.forward * -100f);//速度可调 自行调整}//旋转 x = transform.localEulerAngles.x;y = transform.localEulerAngles.y;}limitation();}}public GameObject box;
//限制区域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;Debug.Log("min.x="+ min.x+ " max.x="+ max.x);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;}}/// <summary>/// 检测是否点击UI/// </summary>/// <param name="mousePosition">鼠标位置</param>/// <returns></returns>private bool IsPointerOverGameObject(Vector2 mousePosition){//创建一个点击事件PointerEventData eventData = new PointerEventData(EventSystem.current);eventData.position = mousePosition;List<RaycastResult> raycastResults = new List<RaycastResult>();//向点击位置发射一条射线,检测是否点击UIEventSystem.current.RaycastAll(eventData, raycastResults);if (raycastResults.Count > 0)//大于0 说明 有UI{return false;}else{return true;}}static float ClampAngle(float angle, float min, float max){if (angle < -360)angle += 360;if (angle > 360)angle -= 360;return Mathf.Clamp(angle, min, max);}//--------------------围绕的物体并且 相机定位物体-------------------//#region//public Transform CenObj;//围绕的物体//private Vector3 Rotion_Transform;//private new Camera camera;bool bo;//private Transform mainCameraTr; //主摄像机//public Transform lookAtTarget; //摄像机看向的目标//private float cameraDistance = 50.0F; //摄像机与看向目标的距离//private float cameraHeight = 800.0F; //摄像机高度//private float cmaeraOffset = 1000.0F; //摄像机的偏移//private float mainCameraMoveSpeed = 1F; //主摄像机移动的速度//private Vector3 lookAtTargetPosition; //看向目标时的位置//private Quaternion lookAtTargetRotation; //看向目标,且旋转//public bool isLookAtAppointTarget = false; //是否看向指定的物体//public void SetInit(Transform CenObj_)//{// Debug.Log("点击了=" + CenObj_.name);// isShuBiao = true;// CenObj = CenObj_;// Rotion_Transform = CenObj.position;// lookAtTarget = CenObj_;// LookAtAppointTarget();// isShuBiao = false;//}//void Update()//{// //if (!isExit)// //{// // Ctrl_Cam_Move();// // Cam_Ctrl_Rotation();// //}//}/ <summary>/ 摄像机看向指定物体的方法/ </summary>//public void LookAtAppointTarget()//{// if (lookAtTarget != null)// {// lookAtTargetPosition = new Vector3(lookAtTarget.transform.position.x + cmaeraOffset,// lookAtTarget.transform.position.y + cameraHeight, lookAtTarget.transform.position.z + cameraDistance);// isLookAtAppointTarget = true;// }// else// {// Debug.LogError(GetType() + "/LookAtAppointTarget()/看向的物体不存在,请检查!!!");// }// if (isLookAtAppointTarget == true)//是否看向物体// {// mainCameraTr.position = Vector3.Lerp(mainCameraTr.position, lookAtTargetPosition, 1 * mainCameraMoveSpeed);// mainCameraTr.LookAt(lookAtTarget);// }// //if (isBack == true)// //{// // mainCameraTr.position = Vector3.Lerp(mainCameraTr.position, lookAtTargetPosition, 10 * mainCameraMoveSpeed);// //}//}#endregion}
}