【Unity】通过鼠标控制相机视角(拉近拉远/选择角度)

今天优化项目的时候,发现观察物体的视角有些问题,所以就自己写了一些代码,同时参考了一些网上大佬们的写法,改了改,写出来了一篇如下的代码:

功能:

鼠标中间控制视角远近

鼠标右键控制视角旋转

 private Transform CamLookPos;//围绕的物体
    private Vector3 Rotion_Transform;

    float distance = 0f;
    float moveSpeed = 0.1f;
    void Start()
    {
        CamLookPos = GameObject.Find("CamLookPos").transform;
        Rotion_Transform = CamLookPos.position;
    }
    void Update()
    {
        Cam_Ctrl_Rotate();
        Cam_Ctrl_Move();

        distance = (transform.position - CamLookPos.position).magnitude;
        //Mathf.Clamp(distance,0.944f,1.397f);

        //Debug.Log(distance);
        0.82   1.57
    }

    private void Cam_Ctrl_Move()
    {
        transform.Translate(Input.GetAxis("Mouse ScrollWheel") * Vector3.forward * moveSpeed);
        if (distance <= 0.6f|| distance >= 1.49f)
        {
            moveSpeed = 0f;
        }
    }

    public void Cam_Ctrl_Rotate()
    {
        var mouse_x = Input.GetAxis("Mouse X");//获取鼠标X轴移动
        var mouse_y = -Input.GetAxis("Mouse Y");//获取鼠标Y轴移动
        if (Input.GetKey(KeyCode.Mouse1))
        {
            transform.RotateAround(Rotion_Transform, Vector3.up, mouse_x * 2);
            transform.RotateAround(Rotion_Transform, transform.right, mouse_y * 2);
        }
    }

你可能感兴趣的:(Unity,unity,ar,游戏引擎,游戏开发)