Unity, leading the protagonist's head toward the ground normal (character align to surface normal)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.