分享

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

 3dC 2016-05-18

标签:style   log   com   代码   使用   src   http   si   it   

计算过程如下:

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;
//用来获取从raycast函数中得到的信息反馈的结构

        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)

标签:style   log   com   代码   使用   src   http   si   it   

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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多