Unity中使用矩阵实现物体跟随

需求:

在某一特殊情况下,物体的子物体需要重新设置新的父物体,但还需要跟随原先物体移动。

1.搭建测试场景:

2.实现:

新建脚本TestFollow,代码如下:

cs 复制代码
public class TestFollow : MonoBehaviour
{
    public RectTransform moveItem;
    public RectTransform followItem;

    public Transform followItemParent;

    // 存储相对变换矩阵
    private Matrix4x4 offsetMatrix;

    void Start()
    {
        Matrix4x4 itemWorldMatrix = moveItem.localToWorldMatrix;
        Matrix4x4 thisWorldMatrix = followItem.localToWorldMatrix;

        // 计算相对矩阵:offset = child * parent^-1
        offsetMatrix = thisWorldMatrix * itemWorldMatrix.inverse;

        followItem.SetParent(followItemParent);
    }

    // Update is called once per frame
    void Update()
    {
        // 使用矩阵计算新的世界位置
        Matrix4x4 itemWorldMatrix = moveItem.localToWorldMatrix;
        Matrix4x4 newWorldMatrix = offsetMatrix * itemWorldMatrix;

        // 从矩阵中提取位置
        Vector3 newPosition = newWorldMatrix.GetColumn(3);
        followItem.position = newPosition;
    }
}

原理:

在游戏开始时计算原父物体与子物体的相对矩阵,在原父物体移动时,通过相对矩阵与原原父物体的世界位置,计算子物体的世界位置。

演示:

相关推荐
Martina_03213 天前
AI生成3D场景导入 Unity/Unreal 后,NPC 总串层?用6步检查导航高度与跨层连接
人工智能·游戏·数学建模·3d·unity·自然语言处理·aigc
小贺儿开发3 天前
Unity 局域网遥控幻灯片展示工具 3.0
科技·http·unity·工具·ppt·通信·网页
WarPigs5 天前
Unity对象不应该使用null传播的问题
unity
每日出拳老爷子6 天前
【VR】【Unity】抓走转放系列21|一天搭完门和抽屉工具槽:小场景按这个次序拼装
unity·vr·驱动·排错·snap zone
淡海水7 天前
02-02-原理篇-分代GC
算法·unity·c#·游戏引擎·.net·gc
小贺儿开发7 天前
Unity 文物新生 会讲故事的文物展墙
人工智能·科技·unity·ai·视频·互动·演示
淡海水7 天前
02-03-原理篇-大对象堆
unity·c#·游戏引擎·.net·gc
WarPigs8 天前
Unity在Create菜单添加创建自定义脚本模板选项
unity
淡海水8 天前
02-01-原理篇-Mark-Sweep与变种算法
算法·unity·c#·游戏引擎·.net·gc
babywang08 天前
Unity笔记--塔防游戏中的ECS架构:从原理到实战的全面解析
unity·ecs架构