Unity3D实现摄像机镜头移动并限制角度实现摄像机镜头移动并限制角度
本文实例为大家分享了Unity3D实现摄像机镜头移动并限制角度的具体代码,供大家参考,具体内容如下
摄像机镜头跟随鼠标移动,并限制上下左右的移动角度
public class ViewFromCream : MonoBehaviour
{
public int speed=5;
public Vector3 vect;
private float xcream;
private float ycream;
public void Update()
{
CreamView();
}
private void CreamView()
{
float x = Input.GetAxis("Mouse X");
float y = Input.GetAxis("Mouse Y");
if (x!=0||y!=0)
{
LimitAngle(60);
LimitAngleUandD(60);
this.transform.Rotate(-y * speed, 0, 0);
this.transform.Rotate(0, x * speed, 0, Space.World);
}
}
/// <summary>
/// 限制相机左右视角的角度
/// </summary>
/// <param name="angle">角度</param>
private void LimitAngle(float angle)
{
vect = this.transform.eulerAngles;
//当前相机x轴旋转的角度(0~360)
xcream = IsPosNum(vect.x);
if (xcream > angle)
this.transform.rotation = Quaternion.Euler(angle,vect.y,0);
else if (xcream < -angle)
this.transform.rotation = Quaternion.Euler(-angle, vect.y, 0);
}
/// <summary>
/// 限制相机上下视角的角度
/// </summary>
/// <param name="angle"></param>
private void LimitAngleUandD(float angle)
{
vect = this.transform.eulerAngles;
//当前相机y轴旋转的角度(0~360)
ycream = IsPosNum(vect.y);
if (ycream > angle)
this.transform.rotation = Quaternion.Euler(vect.x, angle, 0);
else if (ycream < -angle)
this.transform.rotation = Quaternion.Euler(vect.x, -angle, 0);
}
/// <summary>
/// 将角度转换为-180~180的角度
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
private float IsPosNum(float x)
{
x -= 180;