Orient Character to terrain normal with multiple raycasts

Hi guys,

I’m trying to get a character to hug the ground regardless of slope. I’ve been able to do it somewhat successfully using a physics motor, but I’d like to be able to use a character controller. I’ve used the solutions from this answer and tried to come up with a better solution using 4 raycasts and the cross product, but the code doesn’t seem to be working properly. I’m not good at vector math, so any suggestions would be greatly appreciated. Thanks in advance.

public float frontSide;
	public float rightSide;
	Vector3 curNormal = Vector3.up;
	Vector3 frontDirection;
	Vector3 sideDirection;

	
	void Start () {
	
	}
	
	
	void Update () {
		
	RaycastHit hitA;

    if (Physics.Raycast(transform.position + transform.forward * frontSide, -transform.up, out hitA))
    {
    RaycastHit hitB;
    
    if (Physics.Raycast(transform.position - transform.forward * frontSide, -transform.up, out hitB))
	{
  	frontDirection = hitA.point - hitB.point; // check A to B vector and align forward
	}
	}
    RaycastHit hitC;
			
	if (Physics.Raycast(transform.position + transform.right * rightSide, -transform.up, out hitC))
	{
				
	RaycastHit hitD;
			
	if (Physics.Raycast(transform.position - transform.right * rightSide, -transform.up, out hitD))
	{
	sideDirection = hitC.point - hitD.point;
	}
	}
		
	Vector3 newNormal = Vector3.Cross(frontDirection,sideDirection).normalized;
		
	curNormal = Vector3.Lerp(curNormal, newNormal, 4*Time.deltaTime);
	Quaternion grndTilt = Quaternion.FromToRotation(Vector3.up, curNormal);
	transform.rotation = grndTilt; 
		
	}

Yea i think i might try to make a script to post on the wiki to solve this for people roughly the answer is

(assuming you want the feet of a player touching the ground)

// cast a ray at the ground to find the terrain normal
ray.origin = character.transform;
ray.direction = -character.transform.up;

raycast(ray,out raycasthit hitinfo);

axis = vector3.cross( -character.transform.up, -hitinfo.normal)

  angle = Mathf.Atan2( Vector3.Magnitude(axis), Vector3.Dot(-character.transform.up, -hitinfo.normal));

character.transform.rotatearound(axis,angle);

Thats not tested or anything just the pseudo code the axis and angle code though are correct and thats the important thing.

good luck! mark as answered

So I updated my question with a composite vector solution. Let me know if that helps.