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;
    }
}

原理:

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

演示:

相关推荐
xcLeigh15 小时前
Unity基础:C#脚本的创建与挂载——让你的游戏物体活起来
游戏·unity·c#·教程
DaLiangChen1 天前
Vuforia 地面识别案例
unity·ar
江畔柳前堤2 天前
YOLO 目标检测全流程深度剖析
人工智能·yolo·目标检测·计算机视觉·unity·面试·vllm
魔术师Dix2 天前
一个轮子:Luban Skill 制作演示
游戏·unity·ai编程
xcLeigh2 天前
Unity基础:Light灯光组件入门——Directional Light、Point Light与Spotlight
unity·游戏引擎·教程
郝学胜-神的一滴3 天前
[简化版 GAMES 104] 现代游戏引擎 04:从0到1构建你的游戏世界
c++·游戏·unity·游戏引擎·软件工程·unreal engine
是嘟嘟啊4 天前
【Unity DOTS】EntityCommandBuffer 与 JobHandle
unity·ecs·dots·unity dots·job·burst·burstjob
xcLeigh4 天前
Unity基础:Camera相机组件详解——透视投影与正交投影的区别
数码相机·unity·游戏引擎
玖玥拾4 天前
Unity3D RPG 入门项目(二)移动 Bug 修复、环绕相机、NPC 任务系统、UI 穿透处理
unity·游戏引擎