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;
}