You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 23:57:43