首页 > 解决方案 > 将玩家速度整合到相机旋转中

问题描述

我有一个跟随玩家并通过鼠标输入围绕它旋转的相机。我想知道除了鼠标的旋转之外,如何根据玩家的速度为相机添加更轻的旋转。

我有这段代码,但我不确定在 "Input.GetAxis("MouseX")" 后面放什么:

void UpdatePosition()
{
    Debug.Log(playerScript.velocity);

    lookHorizontal = Mathf.Clamp(Input.GetAxis("MouseX") /* + some additional rotation */, -10000, 10000);
    lookVertical = Mathf.Clamp(Input.GetAxis("MouseY") /* + some additional rotation */, -10000, 10000);

    if (lookHorizontal > global.joystickDeadZone || lookHorizontal < -global.joystickDeadZone)
    {
        offset = Quaternion.AngleAxis(lookHorizontal / (1 / global.lookSensitivity * 100), Vector3.up) * offset;
    }
    if (lookVertical > global.joystickDeadZone || lookVertical < -global.joystickDeadZone)
    {
        offset = Quaternion.AngleAxis(lookVertical / (1 / global.lookSensitivity * 100), -this.transform.right) * offset;
    }
    this.transform.position = Vector3.Slerp(this.transform.position, playerRealPosition + offset, positionLerpSpeed * Time.deltaTime);
}

标签: unity3d

解决方案


如果没有输入,则找到相机想要进行的水平旋转,然后将该水平旋转的一部分应用到偏移量(您可以使用Quaternion.RotateTowards它):

void UpdatePosition()
{
    Debug.Log(playerScript.velocity);

    lookHorizontal = Mathf.Clamp(Input.GetAxis("MouseX") /* + some additional rotation */,
            -10000, 10000);
    lookVertical = Mathf.Clamp(Input.GetAxis("MouseY") /* + some additional rotation */, 
            -10000, 10000);

    if (lookHorizontal > global.joystickDeadZone 
            || lookHorizontal < -global.joystickDeadZone)
    {
        offset = Quaternion.AngleAxis(lookHorizontal / (1 / global.lookSensitivity * 100),
                Vector3.up) * offset;
    }
    else
    {
        Vector2 flatPlayerVel = playerScript.velocity;

        if (flatPlayervel != Vector2.zero)
        {
            float autoAdjustSpeed = 20f; // find good constant or way to calculate
                                         // For example, could set to 0f for no auto adjust

            // Find horizontal rotation that velocity is trying to go towards 
            Vector2 flatCameraForward = transform.forward;            
            float angleDiff = Vector2.SignedAngle(flatCameraForward, flatPlayerVel);
            Quaternion goalRotation = Quaternion.AngleAxis(angleDiff, Vector3.up);

            // how much to auto move offset horizontally this frame
            Quaternion adjustRotation = Quaternion.RotateTowards(Quaternion.identity, 
                    goalRotation, autoAdjustSpeed * Time.deltaTime);

            offset = adjustRotation * offset;
        }
    }

    if (lookVertical > global.joystickDeadZone || lookVertical < -global.joystickDeadZone)
    {
        offset = Quaternion.AngleAxis(lookVertical / (1 / global.lookSensitivity * 100), 
                -this.transform.right) * offset;
    }
    this.transform.position = Vector3.Slerp(this.transform.position, 
            playerRealPosition + offset, 
            positionLerpSpeed * Time.deltaTime);
}

推荐阅读