zoukankan      html  css  js  c++  java
  • Unity摄像机围绕物体旋转两种实现方式

    第一种,使用Transform 函数 RotateAround。

    代码如下:

        public Transform target;//获取旋转目标
    
        private void camerarotate() //摄像机围绕目标旋转操作
        {
            transform.RotateAround(target.position, Vector3.up, speed*Time.deltaTime); //摄像机围绕目标旋转
            var mouse_x = Input.GetAxis("Mouse X");//获取鼠标X轴移动
            var mouse_y = -Input.GetAxis("Mouse Y");//获取鼠标Y轴移动
            if (Input.GetKey(KeyCode.Mouse1))
            {
                transform.Translate(Vector3.left*(mouse_x*15f)*Time.deltaTime);
                transform.Translate(Vector3.up*(mouse_y*15f)*Time.deltaTime);
            }
            if (Input.GetKey(KeyCode.Mouse0))
            {
                transform.RotateAround(target.transform.position, Vector3.up, mouse_x*5);
                transform.RotateAround(target.transform.position, transform.right, mouse_y*5);
            }
        }
    
        private void camerazoom() //摄像机滚轮缩放
        {
            if (Input.GetAxis("Mouse ScrollWheel") > 0)
                transform.Translate(Vector3.forward*0.5f);
    
    
            if (Input.GetAxis("Mouse ScrollWheel") < 0)
                transform.Translate(Vector3.forward*-0.5f);
        }
    
    作者:白水SR
    链接:https://www.jianshu.com/p/dbd5c82cfb74
    來源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
    
    


    如果出于某些特殊情况,比如被面试要求不允许使用RotateAround函数,或者非Unity平台等等。可以考虑使用四元数。

    代码如下:

    void MyRotateAround(Vector3 center, Vector3 axis, float angle)
    { Vector3 pos
    = transform.position; Quaternion rot = Quaternion.AngleAxis(angle, axis); Vector3 dir = pos - center; //计算从圆心指向摄像头的朝向向量 dir = rot * dir; //旋转此向量 transform.position = center + dir;//移动摄像机位置 var myrot = transform.rotation; //transform.rotation *= Quaternion.Inverse(myrot) * rot *myrot;//设置角度另一种方法 transform.rotation = rot * myrot; //设置角度 }





  • 相关阅读:
    Fatal error: Maximum execution time of 30 seconds exceeded in
    常见变量命名规则
    Rust使用国内镜像安装依赖
    flutter使用国内镜像源
    7个每天晚上应该坚持的好习惯
    网络数据传输格式的思考
    Deepin安装 ruby 包管理工具 RVM(适用于 Debian 系列)
    C语言数据类型关键字
    win10 powershell禁止运行脚本解决
    Linux 查看系统相关信息(系统发型版本及内核版本等)
  • 原文地址:https://www.cnblogs.com/tangzhenqiang/p/8966882.html
Copyright © 2011-2022 走看看