Search Unity

Handling movement on sloped surfaces - clamping character to sloped surface.

Discussion in 'Scripting' started by rjdfhorn2006, Jun 15, 2016.

  1. rjdfhorn2006

    rjdfhorn2006

    Joined:
    Jun 14, 2010
    Posts:
    141
    I've noticed that a lot of people seem to have this issue but I've yet to find an actual working solution - when a rigidbody-based character controller (I'm not using Unity's character controller) moves down a sloped surface, they will bounce/bunny hop on the way down instead of staying on the surface. I'm building a 3d platformer and ran into this issue - I've tried a fair amount of things but nothing seems to work cleanly. I managed to find a 2D solution here but I can't seem to get it to work cleanly in 3D. Here is my code:

    Code (CSharp):
    1.     void NormalizeSlope()
    2.     {
    3.         // Attempt vertical normalization
    4.         if (isGrounded)
    5.         {
    6.             RaycastHit hit;
    7.             if (Physics.Raycast(floorCheck.position, Vector3.down, out hit, groundCheckDistance))
    8.             {
    9.                 if(hit.collider != null && Mathf.Abs(hit.normal.x) > 0.1f)
    10.                 {
    11.                     // Apply the opposite force against the slope force
    12.                     // You will need to provide your own slopeFriction to stabalize movement
    13.                     rigidbody.velocity = new Vector3(rigidbody.velocity.x - (hit.normal.x * 0.4f), rigidbody.velocity.y, rigidbody.velocity.z); //change 0.6 to y velocity
    14.  
    15.                     //Move Player up or down to compensate for the slope below them
    16.                     Vector3 pos = transform.position;
    17.                     pos.y += -hit.normal.x * Mathf.Abs(rigidbody.velocity.x) * Time.deltaTime * (rigidbody.velocity.x - hit.normal.x > 0 ? 1 : -1);
    18.                     transform.position = pos;
    19.                 }
    20.             }
    21.         }
    22.     }
    With that, I get varying results on surfaces with different slopes. Also, my character jitters. On some slopes, my character even slowly inches their way up the surface. Has anyone else run into this issue? Does anyone have a working solution for this problem?
     
  2. listener

    listener

    Joined:
    Apr 2, 2012
    Posts:
    187
    Is your slope comprised out of single or multiple colliders.

    I had this happen when surface where collider is moving is composed out of multiple colliders no matter if they are perfectly aligned.

    If this is the case making surface from one single collider could solve the issue.