How To Prevent FPS Player From Bouncing Down Slopes

I have this first person movement script that I have been using for a while and I’ve just discovered an issue that I can’t seem to find a fix for.

When I set the CharacterControllers skin width to 0.1 the player doesn’t bounce down slopes which is what I want, but if I set the skinwidth to 0.1 gravity when falling off of slopes is extremely fast. Setting the skinwidth to 0.01 stops the gravity issue but the player starts bouncing down slopes again.

Is their anything in my script that I can do to prevent this?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    [Header("Assignables")]
    public CharacterController controller;
    public Transform GroundCheck;
    public LayerMask GroundMask;

    [Header("Movement")]
    public float WalkSpeed = 0f;
    public float RunSpeed = 0f;
    public bool IsSprinting = false;
    public bool CanSprint = true;
    float PlayerSpeed;

    [Header("Gravity")]
    public float gravity = -9.81f;
    public float GroundDistance = 0.4f;

    Vector3 velocity;
    bool isGrounded;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.LeftShift) && Input.GetKey(KeyCode.W) && CanSprint || Input.GetKey(KeyCode.LeftShift) && Input.GetKey(KeyCode.A) && CanSprint || Input.GetKey(KeyCode.LeftShift) && Input.GetKey(KeyCode.S) && CanSprint || Input.GetKey(KeyCode.LeftShift) && Input.GetKey(KeyCode.D) && CanSprint)
        {
            PlayerSpeed = RunSpeed;
            IsSprinting = true;
        }
        else
        {
            PlayerSpeed = WalkSpeed;
            IsSprinting = false;
        }

        isGrounded = Physics.CheckSphere(GroundCheck.position, GroundDistance, GroundMask);

        if (isGrounded)
        {
            // Only reset the vertical velocity if the player is grounded
            velocity.y = -2f;
        }

        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");
        Vector3 move = transform.right * x + transform.forward * z;

        if (move.magnitude > 1)
            move /= move.magnitude;

        // Adjust velocity for slopes
        velocity = AdjustVelocityToSlope(velocity, move);

        // Finally, apply gravity
        velocity.y += gravity * Time.deltaTime;

        controller.Move(velocity * Time.deltaTime);
    }

    private Vector3 AdjustVelocityToSlope(Vector3 velocity, Vector3 moveDirection)
    {
        var slopeRay = new Ray(transform.position, Vector3.down);

        if (Physics.Raycast(slopeRay, out RaycastHit hitInfo, GroundDistance + 0.1f, GroundMask))
        {
            // Calculate the slope angle
            float slopeAngle = Vector3.Angle(hitInfo.normal, Vector3.up);

            if (slopeAngle > controller.slopeLimit)
            {
                // Calculate the slope adjustment to the movement
                Vector3 slopeDirection = Vector3.Cross(Vector3.Cross(Vector3.up, hitInfo.normal), hitInfo.normal).normalized;
                moveDirection = Quaternion.FromToRotation(moveDirection, slopeDirection) * moveDirection;

                // Apply slope velocity to counteract gravity
                float slopeVelocity = Mathf.Tan(Mathf.Deg2Rad * slopeAngle) * PlayerSpeed;
                velocity.y = -slopeVelocity;
            }
        }

        return moveDirection * PlayerSpeed + Vector3.up * velocity.y;
    }
}
using UnityEngine;

public class SlippyController : MonoBehaviour
{
    CharacterController cc;
    Vector3 velocity;
    RaycastHit hit;

    float gravity=20f;
    float slippy=10f; // How slippery are the slopes?
 
    void Start()
    {
        cc=GetComponent<CharacterController>();
    }

    void Update()
    {
        Vector3 moveDirection=new Vector3(Input.GetAxis("Horizontal"),0,Input.GetAxis("Vertical"));
        if (cc.isGrounded)
        {
            // slide down slopes:
            if (Physics.SphereCast(transform.position,0.5f,Vector3.down,out hit,5f)) // raycast to get the hit normal
            {
                Vector3 dir=Vector3.ProjectOnPlane(Vector3.down,hit.normal); // slope direction
                velocity+=dir*Vector3.Dot(Vector3.down,dir)*gravity*slippy*Time.deltaTime;
            }
            velocity+=moveDirection;
            velocity*=0.95f;   // basic friction
        }
        else
            velocity.y-=gravity*Time.deltaTime;
       
        cc.Move(velocity*Time.deltaTime);
    }
}

This is always “flat” relative to the player’s orientation.

Project this vector onto a plane with Vector3.ProjectOnPlane() and use the result to move directly down the slope.

Pay attention to the two identical arguments: Unity’s docs list them in one order, then discuss them in another order. Always use named arguments when there is ambiguity!!

So there’s at least two issues here:

  1. I would not expect line 55 to be true except when you are on ground too steep to walk on, correct? Look at your greater-than logic.

If that’s not it, then it is time to start debugging.

  1. Do not call .Move() more than once per frame!

Debugging:

Time to start debugging! Here is how you can begin your exciting new debugging adventures:

You must find a way to get the information you need in order to reason about what the problem is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the names of the GameObjects or Components involved?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: How To - Capturing Device Logs on iOS or this answer for Android: How To - Capturing Device Logs on Android

If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

If your problem is with OnCollision-type functions, print the name of what is passed in!

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

“When in doubt, print it out!™” - Kurt Dekker (and many others)

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

Calling Move more than once:

I wrote about this before: the Unity example code in the API no longer jumps reliably.

If you call .Move() twice in one single frame, the grounded check may fail.

I reported it to Unity via their docs feedback in October 2020. Apparently it is still broken:

Here is a work-around:

I recommend you also go to that same documentation page and ALSO report that the code is broken.

When you report it, you are welcome to link the above workaround. One day the docs might get fixed.

If you would prefer something more full-featured here is a super-basic starter prototype FPS based on Character Controller (BasicFPCC):

That one has run, walk, jump, slide, crouch… it’s crazy-nutty!!