Unity中如何让父GameObject跟随子物体的位置与旋转同步?
解决Root Motion导致父物体与子物体不同步的问题
以下是几种可行的方案,可根据你的场景需求选择:
方案1:利用OnAnimatorMove()回调同步父物体
在挂载Animator的敌人模型上添加脚本,通过Unity的OnAnimatorMove()回调(Root Motion应用后触发),将模型的世界空间位置和旋转同步到父物体,再重置模型的本地变换避免偏移:
using UnityEngine; public class SyncParentWithRootMotion : MonoBehaviour { public Transform enemyParent; private Animator _animator; void Awake() { _animator = GetComponent<Animator>(); } void OnAnimatorMove() { if (enemyParent == null || !_animator.applyRootMotion) return; // 将模型的世界位置/旋转同步给父物体 enemyParent.position = transform.position; enemyParent.rotation = transform.rotation; // 重置模型的本地位置与旋转,避免累积偏移 transform.localPosition = Vector3.zero; transform.localRotation = Quaternion.identity; } }
方案2:手动将Root Motion增量应用到父物体
关闭Animator的applyRootMotion,手动提取Root Motion的位移/旋转增量,直接应用到父物体上,让父物体承担所有变换逻辑:
using UnityEngine; public class ApplyRootMotionToParent : MonoBehaviour { public Transform enemyParent; private Animator _animator; void Awake() { _animator = GetComponent<Animator>(); _animator.applyRootMotion = false; } void Update() { if (enemyParent == null) return; // 应用Root Motion的位移增量到父物体 enemyParent.Translate(_animator.deltaPosition, Space.World); // 应用Root Motion的旋转增量到父物体 enemyParent.rotation *= _animator.deltaRotation; } }
方案3:使用Unity内置约束组件
通过Position Constraint和Rotation Constraint组件,让父物体自动跟随敌人模型的位置与旋转:
- 选中父GameObject,依次添加
Component > Layout > Position Constraint和Component > Layout > Rotation Constraint - 在两个约束组件的
Sources列表中,添加敌人模型的Transform - 将约束的
Weight设为1,确保父物体完全跟随模型变换
关于调换父子层级的补充
你提到的将3D模型设为父物体、迁移其他子物体的方案,优点是逻辑直观,所有交互脚本可直接基于模型父物体编写;缺点是需要调整原有脚本的引用关系,若场景层级复杂可能涉及较多修改。
内容的提问来源于stack exchange,提问作者repinSlun
相关产品推荐
相关产品推荐

