Need help with slope physics in a platformer

I’m working on the physics for a rigidbody-based character controller, and I’m having trouble figuring out how to make it so that a character running up a slope doesn’t fly off of it when they run up. I’ve already solved the problem in a movement script where I’m modifying the velocity directly by using a raycast and the normal of the surface, but that leads me to a problem when I’m trying to make a movement script using AddForce:

  • If I use the movement script where it modifies velocity directly instead of AddForce, I have no idea how to keep the concepts of acceleration and deceleration, making it feel very stiff
  • If I keep going with the AddForce version of the movement script, it has better physics, but I have no idea how to make it so the rigidbody sticks to the ground when going from the top of a slope to flat ground - the forces direct the character in the right direction, but the existing forces from the slope ‘fling’ them off anyways

If I can either simulate smoother movement with the direct modification ‘new Vector2’ style of velocity movement or make it so the AddForce script can change the velocity/direction of the existing forces directly when the character is no longer on a slope (something it can already detect, the issue is solely in how it’s actually executed), I’m content with either, but I don’t know how to do either. I imagine it’s something simple I’m not getting quite exactly (I’m a beginner with Unity), but I’ve been stuck on it for embarrassingly long, and I need to get this figured out before I go forward with other parts of the controller/physics.

Try changing your rigidbody’s direction in FixedUpdate without touching the magnitude to align to the ground tangent:

// get the forward direction based on ground tangent (normalize it if it's not already)
Vector3 groundTangent;
rb.velocity = rb.velocity.magnitude * groundTangent;

Then you can use AddForce for acceleration & deceleration but the resulting velocity will always be parallel to the ground, or whatever direction you need based on the situation. You’ll probably want to disable this depending on your character state ie. jumping.

Hope that helps.