Search Unity

Question Weird Quaternion rotation when rotation is alligned with a slope

Discussion in 'Physics' started by OverZhorman, Feb 3, 2024.

  1. OverZhorman

    OverZhorman

    Joined:
    Mar 3, 2021
    Posts:
    4
    Hi!
    I am currently trying to make character's legs align with the slope, while still facing the same direction the camera is looking.
    if (Physics.Raycast(transform.position, -Vector3.up, out hit, 1f, groundCheckLayer))
    {
    //Camera rotation:
    Vector3 cameraPlanarDirection = Vector3.ProjectOnPlane(playerValues.head.forward, Vector3.up).normalized;
    Quaternion cameraPlanarRotation = Quaternion.LookRotation(cameraPlanarDirection, Vector3.up);

    //Joint rotation:
    Quaternion surfaceRotation = Quaternion.FromToRotation(Vector3.up, hit.normal);

    Quaternion targetRotation = surfaceRotation * cameraPlanarRotation;

    joint.targetRotation = targetRotation;
    }

    As you can see in the gif, when the camera is pointing exactly at -z world direction, the leg rotates 360 degrees on the x axis, and I don`t know why or how to fix this.
    Please, oh powerful Quaternion wizards, help this poor soul!
    P.S. the issue is present when using transform.rotation = targetRotation;

    P.P.S. When the ground is horizontal, issue is absent.