1. 程式人生 > >Unity 3D相機視野控制指令碼

Unity 3D相機視野控制指令碼

涉及了視野放大,縮小,旋轉。

相機的跟隨記得放在LateUpdate裡。

private void LateUpdate()
    {
        transform.position = Vector3.Lerp(transform.position, player.transform.position + offset, Time.deltaTime * 5);
        ScrollView();
        RotateView();
    }

    private void ScrollView()
    {
        //獲取滑鼠中鍵滾動的值,向上滾為正值,向下為負值
        float x = Input.GetAxis("Mouse ScrollWheel");
        float distance = offset.magnitude;
        float dis = distance + distance * x * -1;
        //超出指定範圍將不做變化
        if (dis <= 4 || dis >= 10)
        {
            return;
        }
        distance *= x;
        transform.position += -1 * offset.normalized * distance * scrollSpeed;
        //更新offset
        if (Mathf.Abs(x) >= 0.05f)
            offset = transform.position - player.transform.position;
    }

    private void RotateView()
    {
        if (Input.GetMouseButtonDown(1))
            isMouseRightDown = true;
        if (Input.GetMouseButtonUp(1))
            isMouseRightDown = false;

        if(isMouseRightDown)
        {
            //得到滑鼠在滑鼠在x軸和y軸滑動的axis值
            float x = Input.GetAxis("Mouse X");
            float y = Input.GetAxis("Mouse Y");
            transform.RotateAround(player.transform.position, Vector3.up, rotateSpeed * x); //正值為向右,負值為向左

            Vector3 pos = transform.position;
            Quaternion qua = transform.rotation;
            //旋轉的軸為人物的x軸,而不是世界的x軸
            transform.RotateAround(player.transform.position, transform.right, -1 * rotateSpeed * y);
            //如果超出範圍,就還原
            if(transform.eulerAngles.x <= 10 || transform.eulerAngles.x >= 80)
            {
                transform.position = pos;
                transform.rotation = qua;
            }
            offset = transform.position - player.transform.position;
        }
    }