摄像机镜头跟随鼠标移动,并限制上下左右的移动角度

30 篇文章 0 订阅
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;
    if (x < 0)
      return x + 180;
    else return x - 180;   
  }
}

上下的锁定与左右的锁定好像是反的 ,但是能够用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值