Slope direction Vector3 downhill

I’m trying to move the player following a direction Vector, so it moves up and down the slope nicely. My approach works in the uphill direction, but not in the downhill direction. Downhill the Vector’s y component has the wrong sign and I can’t figure out a solution.

MyCode:

//getting inputs
    inputDirection = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
    
    //getting ground info
    RaycastHit hitInfo;
            if(Physics.SphereCast(transform.position + Vector3.up * groundCheckOffset, groundCheckRadius, -Vector3.up, out hitInfo, groundCheckDistance, groundLayer)){
                grounded = true;
                groundAngle = Vector3.SignedAngle(new Vector3(inputDirection.x, 0, inputDirection.y), hitInfo.normal, Vector3.Cross(new Vector3(inputDirection.x, 0, inputDirection.y), hitInfo.normal)) - 90f;
            }
            else{
                grounded = false;
                groundAngle = 0;
            }
    
    //calculating the velocity vector
     velocity = new Vector3(inputDirection.x, Mathf.Sin(groundAngle * Mathf.Deg2Rad), inputDirection.y).normalized * targetSpeed;

I know this probably isn’t a very good approach, but this is what I came up with.

EDIT:
added a (bad) illustration showing my problem: green sphere is the spherecast, red vector is the velocity. When going downhill it should be the dashed vector.

Hey there,

not tested but when you have your hitInfo somehting like this should be able to replace all your code:

velocity = Vector3.Cross(Vector3.Cross(hitInfo.normal, inputDirection), inputDirection).normalized * targetSpeed;

This basically gives you the slope vector in direction of inputDirection +normalization and speed and so on. Is there a reason why you are using a sherecast and not a raycast with -Vector3.up ?

Let me know if something was unclear or you need some further help on this.

EDIT: just saw your grounddetection stuff, forgot about that but i guess you’ll manage to fit that into your code.

To summarize:
the velocity vector is calculated with

velocity = Vector3.Cross(Vector3.Cross(hitInfo.normal, transform.TransformDirection(Vector3(inputDirection.x, 0, inputDirection.y)), hitInfo.normal).normalized * targetSpeed;

This piece of code transforms the local input vector to world space. That way if the player turns around, so does the input vector in world space.

Special Thanks to @Captain_Pineapple for his formula