Make players look direction relative to camera unity

I'm making a third person character controller in unity, I have the Player Moving with a direction and an animation. My question is: how do I make the movement rotation relative to the camera rotation

NOTE: I am Not using transform.translate or any similar method to move the player, I am calculating a rotation using the input vectors and atan2, then moving the player using an animation. So I can't just change the x direction and y direction, I can only change the y rotation

my current player look code

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

Upvotes: 0

Views: 1692

Answers (2)

Mr. For Example
Mr. For Example

Reputation: 4313

I currently don't have time to test on Unity, so I give you some pseudocode to help you with your problem

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

Upvotes: 2

bre_dev
bre_dev

Reputation: 572

You might consider upgrading your project to use the new Starter Asset from Unity, it has both an FPS and third person character controllers which both support exactly what you are trying to do.

It also uses cinemachine which is really good in avoiding jitter and motion sickness when the character rotates.

https://assetstore.unity.com/packages/essentials/starter-assets-third-person-character-controller-196526

Upvotes: 0

Related Questions