There’s an open-source custom character controller that kind of does what you want to do
Maybe you can find something inside the script?