unity3d 使玩家看相对于摄像机单位的方向

x8goxv8g  于 2023-01-05  发布在  其他
关注(0)|答案(2)|浏览(131)

我正在做一个第三人称角色控制器,我有一个方向和动画的球员移动。我的问题是:如何使机芯相对于相机旋转
注意:我没有使用transform.translate或任何类似的方法来移动播放器,我使用输入向量和atan2来计算旋转,然后使用动画来移动播放器。所以我不能只改变x方向和y方向,我只能改变y旋转
我当前的播放器外观代码

Vector3 CalculateRotation(float H, float V)
{
    IsTurning = IsMoving(H, V);
    if (IsTurning) {
        angle = Mathf.RoundToInt(Mathf.Atan2(V, -H) * Mathf.Rad2Deg);
        IsTurned = false;

        ani.SetBool("isWalking", true);
        return new Vector3(0, Mathf.RoundToInt(angle), 0);
    }
    else
    {
        ani.SetBool("isWalking", false);
    }

    return new Vector3(0, Mathf.RoundToInt(CurrentRotation.y), 0);
          
}

void LookTorwards(Vector3 T_Angle)
{

    NewRotation = T_Angle - CurrentRotation;
    NewRotation.y = Mathf.Repeat(NewRotation.y + 180f, 360f) - 180f;
    if (NewRotation.y == 180)
    {
        NewRotation.y -= 1;
    }

    if (TargetRotation.y == CurrentRotation.y)
    {
        IsTurned = true;
        return;
    }

    if (NewRotation.y > 0)
    {
        transform.Rotate(new Vector3(0, RotationSpeed, 0));
        CurrentRotation.y += RotationSpeed;
    }
    else if (NewRotation.y < 0)
    {
        transform.Rotate(new Vector3(0, -RotationSpeed, 0));
        CurrentRotation.y -= RotationSpeed;
    }
}
wdebmtf2

wdebmtf21#

我目前没有时间在Unity上进行测试,所以我给予了一些伪代码来帮助您解决问题

// Get the direction of where the player should ahead in world space
Vector3 hMoveDir = cameraTransform.right * movementHorizontal;
Vector3 vMoveDir= cameraTransform.forward * movementVertical;
Vector3 moveDir = hMoveDir + vMoveDir;

// Create the rotation we need according to moveDir
lookRotation = Quaternion.LookRotation(moveDir);

// Rotate player over time according to speed until we are in the required rotation
playerTransform.rotation = Quaternion.Slerp(playerTransform.rotation, lookRotation , Time.deltaTime * RotationSpeed);
omqzjyyz

omqzjyyz2#

您可以考虑升级您的项目以使用Unity的新Starter资源,它同时具有FPS和第三人称角色控制器,这两个角色控制器都支持您正在尝试做的事情。
它还使用了Cinemachine,这真的很好地避免了角色旋转时的抖动和晕动病。
https://assetstore.unity.com/packages/essentials/starter-assets-third-person-character-controller-196526

相关问题