The calculation process is as follows:
1, by the center of the protagonist Raycast a vertical ray to obtain the main role of the ground normal, as the protagonist of the Newup.
2, according to the protagonist forward and newup calculate Newforward.
3, use Quaternion.lookrotation (Newforward, newup) to get the protagonist new rotation.
Results
Code:
Note, the code here suppose we character use a capsulecollider and the floors ' layermask are ' floor '.
//.. If yours ' isn't, you should make some.
Raycasthit Hitinfo;
Vector3 capsulecollidercenterinworldspace=getcomponent<capsulecollider> (). Transform. Transformpoint (getcomponent<capsulecollider> (). Center);
BOOL Ishit=physics.raycast (capsulecollidercenterinworldspace,new Vector3 (0f,-1f,0f), out hitinfo,100f, Layermask.getmask ("floor"));
Vector3 forward=getcomponent<rigidbody> (). Transform.forward;
Vector3 newup;
if (ishit) {
Newup = Hitinfo.normal;
} else {
Newup = Vector3.up;
}
Vector3 left = Vector3.cross (forward,newup);//note:unity use left-hand system, and vector3.cross obey left-hand rule.
Vector3 Newforward = Vector3.cross (newup,left);
Quaternion oldrotation=getcomponent<rigidbody> (). transform.rotation;
quaternion newrotation = quaternion.lookrotation (Newforward, newup);
Float ksoftness=0.1f;//if don't want softness, change the value to 1.0f
Getcomponent<rigidbody> (). Moverotation (Quaternion.lerp (oldrotation,newrotation,ksoftness));
Unity, leading the protagonist's head toward the ground normal (character align to surface normal)