码迷,mamicode.com
首页 > 编程语言 > 详细

unity, 让主角头顶朝向等于地面法线(character align to surface normal)

时间:2015-03-31 14:18:34      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

计算过程如下:

1,通过由主角中心raycast一条竖直射线获得主角所在处地面法线,用作主角的newUp。

2,根据主角forward和newUp计算newForward。

3,使用Quaternion.LookRotation (newForward, newUp)获得主角新的rotation。

结果如图:

技术分享   技术分享

代码:

     //note, the code here suppose our character use a capsuleCollider and the floors‘ layerMask is "floor"..

     //..if yours‘ is not, you should make some change.


        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 do not want softness, change the value to 1.0f
        GetComponent<Rigidbody> ().MoveRotation (Quaternion.Lerp(oldRotation,newRotation,kSoftness));

unity, 让主角头顶朝向等于地面法线(character align to surface normal)

标签:

原文地址:http://www.cnblogs.com/wantnon/p/4380554.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!