Custom Collide and Slide algorithm

I have been trying to implement a top down version of the collide and slide algorithm, similar to the move_and_slide() in godot, insprided from this video:

But the problem I am having is that when going to a wide angle wall I get jitters.

    private Vector3 CollideAndSlide(Vector3 vel, Vector3 pos, int depth) {
        if (depth >= MaxBounces) {
            return Vector3.zero;
        }
        
        float radius = 0.5f;
        Vector3 dir = vel.normalized;
        float dist = vel.magnitude + SkinWidth;
        if (Physics.SphereCast(pos, (radius - SkinWidth), dir, out var hit, dist)) {
            Vector3 snapToSurface = dir * (hit.distance - SkinWidth);
            Vector3 leftOver = vel - snapToSurface;
            if (snapToSurface.magnitude <= SkinWidth) {
                snapToSurface = Vector3.zero;
            }

            float scale = 1 - Vector3.Dot(
                new Vector3(hit.normal.x, hit.normal.y, 0f).normalized, 
                - new Vector3(vel.x, vel.y, 0f).normalized
            );
            float mag = leftOver.magnitude;
            leftOver = Vector3.ProjectOnPlane(leftOver, hit.normal).normalized;
            print(leftOver);
            leftOver *= mag;
            // leftOver *= scale;

            return snapToSurface + CollideAndSlide(leftOver, pos + snapToSurface, depth + 1);
        }
        
        return vel;
    }

When I uncomment the “leftOver *= scale;” part the corner jitter dissappears but then I get slowing of movement when sliding across. If I don’t want that the jitter comes back. I would really appreciate any help.

You tagged it 2D physics but your code is using 3D physics. Want me to change that to “Physics”?

Yes please, very sorry.

Not a problem at all!

Because that code wasn’t telling me much and I only had a hunch that at some point, the angle of the surface will cause the velocity to be zero or negative but as you bounce back to the less steep wall you accelerate once again, that this would end with a back-and-forth cycle.

So I just put this into Gemini, here’s the answer you could try because I couldn’t explain this nearly as well let alone provide help with improving the code. :wink:

PS: Character controllers and collisions are super-duper challenging. Unless you’re having fun working on that, you’re better off picking one of the gazillion existing controllers and go with that. Kinematic Character Controller on the store is solid and free.