[Unity] Control the camera angle of view through the mouse (zoom in and out/select the angle)

When I was optimizing the project today, I found that there was some problem with the viewing angle of the object, so I wrote some code by myself, and at the same time referred to the writing methods of some online bigwigs, changed it, and wrote a piece of code as follows:

Function:

The middle of the mouse controls the viewing angle

Right mouse button controls viewing angle rotation

 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);
        }
    }

Guess you like

Origin blog.csdn.net/CSDN_6954/article/details/121249441