Unity鼠标移动平滑旋转相机

      物体旋转可以选择欧拉角或者四元素进行,我这里为了旋转平滑用了四元素的Quaternion.Slerp方法,但是如果上下左右旋转同时作用在相机上,旋转的时候会出现倾斜.为了解决这个问题我给相机添加一个父物体,父物体控制水平旋转,相机控制垂直旋转.

      在场景中创建一个相机父物体,相机的位置和旋转默认归零.完整代码如下:

public float XSensitivity = 2f;
    public float YSensitivity = 2f;
    //是否平滑
    public bool smooth;
    //平滑参数
    public float smoothTime = 5f;

    //相机父物体
    private Quaternion targetRot;
    //相机
    private Quaternion cameraRot;

    private void Start()
    {
        targetRot = transform.parent.localRotation;
        cameraRot = transform.localRotation;
    }

    private void Update()
    {
        //按下右键旋转
        if (!Input.GetMouseButton(1)) return;
        LookRotation();
    }

    public void LookRotation()
    {
        float yRot = Input.GetAxis("Mouse X") * XSensitivity;
        float xRot = Input.GetAxis("Mouse Y") * YSensitivity;

        targetRot *= Quaternion.Euler(0f, yRot, 0f);
        cameraRot *= Quaternion.Euler(-xRot, 0f, 0f);

        if (smooth)
        {
            transform.parent.localRotation = Quaternion.Slerp(transform.parent.localRotation, targetRot, smoothTime * Time.deltaTime);
            transform.localRotation = Quaternion.Slerp(transform.localRotation, cameraRot, smoothTime * Time.deltaTime);
        }
        else
        {
            transform.parent.localRotation = targetRot;
            transform.localRotation = cameraRot;
        }
    }

把脚本拖拽到相机上即可.

你可能感兴趣的:(Unity3D)