Search Unity

Maintaining proper forward rotation while moving through a curved tube

Discussion in 'Physics' started by lpye, May 31, 2018.

  1. lpye

    lpye

    Joined:
    Aug 2, 2012
    Posts:
    30
    I'm trying to create a scene where the character is moving through a tunnel with no gravity but is "stuck" to the interior of the tunnel. I have disabled gravity and am using a downward force to keep them attached. Using a typical WASD arrangement, the character should be able to move forward or backward through the tunnel while moving left or right causes them to move around the inside surface of the tunnel while retaining their local "upward" orientation to that interior surface. What is also important is that I do not want them to spin on their local Y when moving. That is, their forward direction should always be downward through the tunnel.

    The problem I'm having is when the player encounters a curve in the tunnel. During a straight portion of the tunnel, moving sideways retains the forward direction no matter how much side to side movement I use. When I hit the curve however, my rotation code is causing me to... I don't know how to describe it, but the character seems to turn "back" in the direction I came from a little, so that if, for example, I kept moving left I would eventually spin and be facing the side of the tunnel such that forward motion just causes the character to circle around at that slice of the tunnel.

    Here is the portion of my FixedUpdate() routine where I try to handle the rotation. Note that I'm attempting to remove the Y-axis spin of the Quaternion before slerping to apply the rotation.

    Code (CSharp):
    1.         if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.down), out hit)) {
    2.             Quaternion rotQuat = Quaternion.FromToRotation(Vector3.up, hit.normal);
    3.             rotQuat = Quaternion.Euler(new Vector3(rotQuat.eulerAngles.x
    4.                                                    , 0f
    5.                                                    , rotQuat.eulerAngles.z));
    6.  
    7.             transform.rotation = Quaternion.Slerp(
    8.                 transform.rotation
    9.                 , rotQuat
    10.                 , 0.5f
    11.                 );
    12.         }
    Thanks in advance...