许可优化
许可优化
产品
产品
解决方案
解决方案
服务支持
服务支持
关于
关于
软件库
当前位置:服务支持 >  软件文章 >  Unity Foot IK反向动力学应用逻辑讲解,脚步贴合地面

Unity Foot IK反向动力学应用逻辑讲解,脚步贴合地面

阅读数 14
点赞 0
article_banner


using Sirenix.OdinInspector;

using UnityEngine;

namespace FootIKSystem

{

   [RequireComponent(typeof(Animator))]

   public class SimpleFootIK : MonoBehaviour

   {

       [Header("核心参数")]

       [SerializeField, Range(0, 1)] public float Weight = 1f;

       [SerializeField] public LayerMask Ground = 1;

       [Header("细节参数")]

       [SerializeField, LabelText("最大跨步高度")] public float MaxStep = 0.5f;

       [SerializeField, LabelText("脚底检测半径")] public float FootRadius = 0.15f;

       [SerializeField, LabelText("脚底离地偏移")] public float Offset = 0f;

       [Header("骨盆跟随参数")]

       [SerializeField, LabelText("骨盆跟随脚的权重 ")] //1表示完全跟随较低的那只脚

       public float PelvisWeight = 0.75f;

       [SerializeField, LabelText("骨盆高度变化的平滑速度(越大越灵敏)")]

       public float HipsLerp = 8f;

       [Header("脚步贴合参数")]

       [SerializeField, LabelText("脚高度插值速度(越大越贴地,越小越柔和)")]

       public float FootPosLerp = 12f;

       [SerializeField, LabelText("脚旋转插值速度(度/秒)")]

       public float FootRotLerp = 720f; // deg/sec

       Animator anim;

       Vector3 lIKPos, rIKPos,//左右脚IK位置

       lNormal, rNormal;//左右脚法线

       Quaternion lIKRot = Quaternion.identity, rIKRot = Quaternion.identity;//左右脚IK旋转

       float lastPelvisOffset;//上一个骨盆偏移量

       float lLastHeight, rLastHeight;//左右脚上一个高度

       Quaternion lLastRot = Quaternion.identity, rLastRot = Quaternion.identity;//左右脚上一个旋转

       bool leftFootIsGrounded, rightFootIsGrounded;//左右脚是否踩到地面

       float falloff = 1f;//整体淡入淡出权重

       void Start()

       {

           anim = GetComponent<Animator>();

       }

       void FixedUpdate()

       {

           if (Weight <= 0f || anim == null) return;

           // 计算每只脚的目标落点和目标旋转

           SolveFoot(HumanBodyBones.LeftFoot, ref lIKPos, ref lNormal, ref lIKRot, ref leftFootIsGrounded);

           SolveFoot(HumanBodyBones.RightFoot, ref rIKPos, ref rNormal, ref rIKRot, ref rightFootIsGrounded);

           bool anyFootIsGrounded = leftFootIsGrounded || rightFootIsGrounded;

           // 计算淡入淡出权重 当至少有一只脚触地时 设置权重为1

           falloff = Mathf.MoveTowards(

               falloff,

               anyFootIsGrounded ? 1f : 0f,

               10f * Time.fixedDeltaTime) * Weight;

       }

       void OnAnimatorIK(int layerIndex)

       {

           if (Weight <= 0f || anim == null) return;

           // 先做骨盆高度调整(避免腿被拉长),再分别设置左右脚的 IK 位置与旋转。

           MovePelvis();

           ApplyFoot(AvatarIKGoal.LeftFoot, lIKPos, lNormal, lIKRot, ref lLastHeight, ref lLastRot);

           ApplyFoot(AvatarIKGoal.RightFoot, rIKPos, rNormal, rIKRot, ref rLastHeight, ref rLastRot);

       }

       /// <summary>

       /// 调整骨盆/身体中心高度:取较低脚的偏移作为参考

       /// </summary>

       void MovePelvis()

       {

           //通过 PelvisWeight 控制跟随比例,避免过度上下抖动

           //通过 HipsLerp 进行平滑,减少瞬时跳变

           //叠加 Offset 作为统一的整体抬升,模拟鞋底厚度或动画偏差

           // Debug.Log("当前角色位置:" + anim.transform.position.y);

           float lOffset = lIKPos.y - anim.transform.position.y;

           // Debug.Log("左脚偏移:" + lOffset);

           float rOffset = rIKPos.y - anim.transform.position.y;

           float targetOffset = Mathf.Min(lOffset, rOffset) * (PelvisWeight * falloff);

           lastPelvisOffset = Mathf.MoveTowards(lastPelvisOffset, targetOffset, HipsLerp * Time.deltaTime);

           Vector3 body = anim.bodyPosition;

           body.y += lastPelvisOffset + Offset;

           anim.bodyPosition = body;

       }

       /// <summary>

       /// 应用单脚的 IK

       /// </summary>

       /// <param name="foot">目标脚</param>

       /// <param name="ikPos">目标位置</param>

       /// <param name="normal">目标法线</param>

       /// <param name="ikRot">目标旋转</param>

       /// <param name="lastHeight">上一个高度</param>

       /// <param name="lastRot">上一个旋转</param>

       void ApplyFoot(AvatarIKGoal foot, Vector3 ikPos, Vector3 normal,

           Quaternion ikRot,

           ref float lastHeight,

           ref Quaternion lastRot)

       {

           //获取当前脚的IK信息 :位置和旋转

           Vector3 footPos = anim.GetIKPosition(foot);

           Quaternion footRot = anim.GetIKRotation(foot);

           //将脚的位置和目标位置转为本地坐标

           footPos = anim.transform.InverseTransformPoint(footPos);

           Vector3 localTarget = anim.transform.InverseTransformPoint(ikPos);

           //平滑计算脚应高到的高度

           lastHeight = Mathf.MoveTowards(lastHeight, localTarget.y, FootPosLerp * Time.deltaTime);

           //应用偏移

           footPos.y += lastHeight;

           //将脚的位置转回世界坐标 并应用偏移

           footPos = anim.transform.TransformPoint(footPos);

           footPos += normal * Offset;

           // 将脚的朝向对齐至地面法线

           // 原来的方法:计算相对旋转差值并平滑应用

           // Quaternion targetRot = Quaternion.Inverse(footRot) * ikRot;

           // lastRot = Quaternion.RotateTowards(lastRot, targetRot, FootRotLerp * Time.deltaTime);

           // footRot *= lastRot;

           // 更简单的平滑插值方法

           footRot = Quaternion.Slerp(footRot, ikRot, FootRotLerp * Time.deltaTime);

           anim.SetIKPosition(foot, footPos);

           anim.SetIKRotation(foot, footRot);

           anim.SetIKPositionWeight(foot, falloff);

           anim.SetIKRotationWeight(foot, falloff);

       }

       /// <summary>

       /// 计算脚的目标位置/法线/旋转

       /// </summary>

       void SolveFoot(HumanBodyBones bone,

           ref Vector3 ikPos,

           ref Vector3 normal,

           ref Quaternion ikRot,

           ref bool grounded)

       {

           //获取左右脚骨骼的位置

           Vector3 footBonePos = anim.GetBoneTransform(bone).position;

           // Debug.Log(anim.transform.position.y);

           footBonePos.y = anim.transform.position.y + MaxStep;

           // Debug.Log("脚底位置:" + footBonePos.y);

           if (normal != Vector3.zero)

           {

               footBonePos -= normal * Offset;

           }

           #region 可视化调试

           // 可视化 SphereCast 起点(红色球体轮廓)

           DrawSphereWireframe(footBonePos, FootRadius, Color.green);

           Vector3 castDirection = Vector3.down;

           float castDistance = MaxStep * 2f;

           Vector3 castEnd = footBonePos + castDirection * castDistance;

           // 可视化 SphereCast 射线(绿色)

           Debug.DrawRay(footBonePos, castDirection * castDistance, Color.green);

           #endregion

           RaycastHit hit;

           if (Physics.SphereCast(footBonePos, FootRadius, Vector3.down, out hit, MaxStep * 2f, Ground))

           {

               ikPos = hit.point;

               normal = hit.normal;

               Vector3 axis = Vector3.Cross(Vector3.up, hit.normal);

               float angle = Vector3.Angle(Vector3.up, hit.normal);

               ikRot = Quaternion.AngleAxis(angle, axis);

               //脚到底面高度差小于 MaxStep 视为已落地

               float feetHeight = anim.transform.position.y - hit.point.y;

               grounded = feetHeight < MaxStep;

               #region 可视化调试

               // 可视化命中点(红色球体轮廓)

               DrawSphereWireframe(hit.point, FootRadius, Color.green);

               // 可视化法线(蓝色)

               Debug.DrawRay(hit.point, normal * 0.3f, Color.blue);

               #endregion

           }

           else

           {

               grounded = false;

               ikPos = new Vector3(ikPos.x, anim.transform.position.y - MaxStep, ikPos.z);

               ikRot = Quaternion.identity;

               #region 可视化调试

               // 可视化未命中时的终点(红色球体轮廓)

               DrawSphereWireframe(castEnd, FootRadius, Color.yellow);

               #endregion

           }

       }

       /// <summary>

       /// 绘制球体线框(用于可视化 SphereCast)

       /// </summary>

       void DrawSphereWireframe(Vector3 center, float radius, Color color)

       {

           // 绘制三个方向的圆环来模拟球体

           int segments = 16;

           float angleStep = 360f / segments;

           // XY 平面(水平圆)

           Vector3 prevPoint = center + new Vector3(radius, 0, 0);

           for (int i = 1; i <= segments; i++)

           {

               float angle = i * angleStep * Mathf.Deg2Rad;

               Vector3 point = center + new Vector3(Mathf.Cos(angle) * radius, Mathf.Sin(angle) * radius, 0);

               Debug.DrawLine(prevPoint, point, color);

               prevPoint = point;

           }

           // XZ 平面(水平圆)

           prevPoint = center + new Vector3(radius, 0, 0);

           for (int i = 1; i <= segments; i++)

           {

               float angle = i * angleStep * Mathf.Deg2Rad;

               Vector3 point = center + new Vector3(Mathf.Cos(angle) * radius, 0, Mathf.Sin(angle) * radius);

               Debug.DrawLine(prevPoint, point, color);

               prevPoint = point;

           }

           // YZ 平面(垂直圆)

           prevPoint = center + new Vector3(0, radius, 0);

           for (int i = 1; i <= segments; i++)

           {

               float angle = i * angleStep * Mathf.Deg2Rad;

               Vector3 point = center + new Vector3(0, Mathf.Cos(angle) * radius, Mathf.Sin(angle) * radius);

               Debug.DrawLine(prevPoint, point, color);

               prevPoint = point;

           }

       }

   }

}


免责声明:本文系网络转载或改编,未找到原创作者,版权归原作者所有。如涉及版权,请联系删

相关文章
技术文档
QR Code
微信扫一扫,欢迎咨询~
customer

online

联系我们
武汉格发信息技术有限公司
湖北省武汉市经开区科技园西路6号103孵化器
电话:155-2731-8020 座机:027-59821821
邮件:tanzw@gofarlic.com
Copyright © 2023 Gofarsoft Co.,Ltd. 保留所有权利
遇到许可问题?该如何解决!?
评估许可证实际采购量? 
不清楚软件许可证使用数据? 
收到软件厂商律师函!?  
想要少购买点许可证,节省费用? 
收到软件厂商侵权通告!?  
有正版license,但许可证不够用,需要新购? 
联系方式 board-phone 155-2731-8020
close1
预留信息,一起解决您的问题
* 姓名:
* 手机:

* 公司名称:

姓名不为空

姓名不为空

姓名不为空
手机不正确

手机不正确

手机不正确
公司不为空

公司不为空

公司不为空