Getting the RaycastHit.normal from a boxcast when in the middle of two surfaces

I’m trying to align my charatcter to the ground its standing on. To get the normal I do a boxcastall and then get the average between the normals of all surfaces hit. The problem is that at specific angles when between a slope and regular ground, the groundNormal seems to alternate between to values, for example (0, 1, 0) and (0, 0.97, 0.26), wich causes the character to jitter between the two alignments. Here is the script:

 void Start()
    {
        rb = GetComponent<Rigidbody>();
        rb.freezeRotation = true;

        isJumpingTimer = 0f;

        maxSpeed = baseMaxSpeed;
    }

    // Update is called once per frame
    void Update()
    {
   
       
        float InputX = Input.GetAxisRaw("Horizontal");
        float InputY = Input.GetAxisRaw("Vertical");

        Vector3 camForward = new Vector3(cam.transform.forward.x, 0f, cam.transform.forward.z);
        moveDirection = (camForward * InputY) + (cam.transform.right * InputX);


        if (moveDirection != Vector3.zero) //rotate character
        {
            Quaternion toRotation = Quaternion.LookRotation(Vector3.ProjectOnPlane(moveDirection, transform.up).normalized, transform.up);

            rb.rotation = Quaternion.Slerp(transform.rotation, toRotation, rotationSpeed * Time.deltaTime);
        }
        else
        {
            Quaternion toRotation = Quaternion.LookRotation(transform.forward, transform.up);

            rb.rotation = Quaternion.Slerp(transform.rotation, toRotation, rotationSpeed * Time.deltaTime);
        }

        jumpStart();
        //Debug.Log(rb.velocity.magnitude);
    }

    void FixedUpdate()
    {
        alignToGround();
        move();
        Jump();
        capSpeed();
    }



    void move()
    {
        if (onGround)
        {
            moveDirection = Vector3.ProjectOnPlane(moveDirection, transform.up).normalized;
            rb.AddForce(moveDirection.normalized * speed, ForceMode.Force);

        }
        else
        {
            rb.AddForce(moveDirection.normalized * speed * airMultiplier, ForceMode.Force);
            if (rb.velocity.y > - gravityForce/2)
                 rb.AddForce(Vector3.down * gravityForce, ForceMode.Force);
        }
    }

    private void jumpStart()
    {
        if (Input.GetKeyDown(jumpKey) && onGround && !isJumping)
            doJump = true;
    }

    private void Jump()
    {
        if (doJump)
        {
            // reset y velocity
            rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);

            rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
            doJump = false;
            isJumping = true;
            isJumpingTimer = 0f;
        }
        else if (isJumping)
        {
            isJumpingTimer += Time.deltaTime;

            if (isJumpingTimer >= maxJumpTime)
            {
                isJumping = false;
                if (rb.velocity.y > 0)
                    rb.velocity = new Vector3(rb.velocity.x, smoothJump, rb.velocity.z);
            }

            if (!Input.GetKey(jumpKey) && isJumpingTimer >= minJumpTime && isJumping)
            {
                isJumping = false;
                if (rb.velocity.y > 0)
                    rb.velocity = new Vector3(rb.velocity.x, smoothJump, rb.velocity.z);
            }
        }
    }

    void capSpeed()
    {
        if (onGround)
        {
            if (rb.velocity.magnitude > maxSpeed)
                rb.velocity = rb.velocity.normalized * maxSpeed;
        }
        else
        {
            Vector3 horizontalVel = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
            if (horizontalVel.magnitude > maxSpeed)
            {
                horizontalVel = horizontalVel.normalized * maxSpeed;
                rb.velocity = new Vector3(horizontalVel.x, rb.velocity.y, horizontalVel.z);
            }
        }
    }




    void alignToGround()
    {

        if (isJumping && rb.velocity.y > 0)
        {
            onGround = false;
            changeState();
            return;
        }

        //else
        Ray ray = new Ray(transform.position, -Vector3.up);
        RaycastHit[] info = Physics.BoxCastAll(rb.position, new Vector3(0.4f, 0.1f, 0.75f), -transform.up, rb.rotation, rayLenght, groundMask);
       


        if (Physics.BoxCast(rb.position, new Vector3(0.4f, 0.1f, 0.75f), -transform.up, rb.rotation, rayLenght, groundMask))
        {
            Vector3 groundNormal = Vector3.zero;
            foreach(RaycastHit r in info)
            {
                groundNormal += r.normal;
            }
            groundNormal = groundNormal.normalized;
            Debug.Log(groundNormal);
            rb.rotation = Quaternion.FromToRotation(transform.up, groundNormal) * transform.rotation;
            onGround = true;
            //Debug.Log(info[0].point);
        }
        else onGround = false;

        changeState();

        Debug.DrawRay(transform.position, -Vector3.up * rayLenght, Color.red);
        Debug.DrawRay(transform.position, moveDirection.normalized * 5, Color.blue);
    }


    void OnDrawGizmosSelected()
    {
        // Draw a semitransparent red cube at the transforms position
        Gizmos.color = new Color(1, 0, 0, 0.5f);
        Gizmos.DrawCube(transform.position + new Vector3(0, 2, 0), new Vector3(0.8f, 0.8f, 1.5f));
    }

    public void changeState()
    {
        if (onGround)
        {
            if (moveDirection != Vector3.zero)
                rb.drag = groundDrag;
            else rb.drag = stillDrag;
            isJumping = false;
        }
        else if (!onGround)
        {
            rb.drag = airDrag;
        }
    }

The problem most likely lies in the alignToGround function, but I post the whole script as it may be somewhere else as well.

Also bonus question: how can I check wether BoxcastAll hit without doing another boxcast?

Instead of doing another BoxCast you can just check the length of the info array.

So replace line 141 with:

if (info.Length>0)

That works, thanks.

To address your primary issue: Even when you average all the surface normals you still will get a “snappy” behaviour as soon as a new surface comes into the mix. Though it may not be as heavy as just snapping to the one single normal below your character.

In order to get a smoother transition one may suggest to “slerp” / interpolate from the current old normal to the new one so it’s not as sudden. However this would not fix issues when a surface is right at the edge of your box cast and may sometimes be hit and sometimes it isn’t due to minor jitter.

A better approach would be to weight the normals based on the distance of the hit point to the characters center. The further outside a normal is, the less impact it should have, the closer it is to the center, the more weight it should have. That way you automatically interpolate between the normals. Also a normal that just enters the box cast at the edge will have almost no impact on the resulting normal.

In order to pull that off you first need to transform the hit points into the local space of your character. Then just ignore the y component ( set it to 0) so we only get the horizontal distance. The length of that vector would be that distance. Next up we normalize the distance so it’s essentially 0 to 1 where 0 is the center and 1 essentially the out most distance. So we just need to divide by the “diagonal radius” of your box. Now there are two ways how to inversly map the distance to a weight. You could either subtract it from 1 which would be a linear mapping or you could do 1/d. The 1/d approach would of course be a non-linear mapping where points close to the center would even tend to infinity would points close to the edge would essentially be 1. Though during the normalizing step we could divide by a smaller number so the outer normals would get even less weight. When you use the linear approach it’s important that the value is really normalized and never goes above 1. Otherwise you would get negative weights which would not be good ^^.

Once you have the weigths you just need to multiply each normal with the corresponding weight before summing them together and renormalizing it.

When the box cast isn’t that wide and you move relatively fast, it could still end up a bit snappy. However you can always add some smoothing on top

Thanks for the in depth response. Honestly I only understand about 70% of what you just said, but at least now I know what to look for.

The problem that I’m trying to solve is actually a bit different than what you understood, but your response will still help me.

My problem is that when my character stands in between two surfaces, even when completely still and with no changes to the surfaces, begins to alternate between two different rotations continuously. Essentialy, I needed to understand why my function gives a different groundNormal even tough the conditions haven’t changed.

I realized now while writing this that the problem is most likely that the angulation of the boxcast is changing with the character’s rotation, wich sometimes causes the boxcast to alternate between detecting only one surface, and detecting both, wich changes the groundNormal. I still need to work on a solution, but understanding the problem is still huge progress.