- Home /
Best way to rotate player object to match the ground smoothly.
I'm hoping there's a really simple solution I've somehow missed, but anyway:
Currently, in order to rotate the player object to the angle of the ground, I'm using a raycast down and Quaternion.LookRotation to match the player to the normal returned. Technically this works, as it rotates the player to the angle of the ground, and doesn't look to bad once I lerp the rotation.
The issue can hopefully be explained with the image below. (It's a 3D game, so square = cube)
Since the rotation relies entirely on one normal vector, transitions over rough terrain and at the bottom/top of slopes don't work particularly smoothly, even with lerping. Small bumps/ground objects just send the player object mad.
I've tried using a front and back raycast and then using the average of the two normals, but this completely breaks on slopes, and is still affected by small objects. I've also tried disabling rigidbody rotation contraints, which works to a degree, but has my character frequently tripping over.
Is there a simple way to evaluate the average angle of the ground beneath an object so I can rotate to match it.
Answer by HKDuskraven · Oct 15, 2017 at 12:58 AM
To anyone who finds this googling in 12 years, I solved it.
Turns out the solution was in fact using two raycasts, one at the front, one at the back, then using their hit locations to get an upright direction from a vector3 cross product.
upright = Vector3.Cross(transform.right, -(fHit.point - bHit.point).normalized)
transform.rotation = Quaternion.LookRotation(Vector3.Cross(transform.right, upright));
Not quite 12 years, but thanks! You're solution gives a really smooth result.