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

原理:

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

演示:

相关推荐
HH‘HH1 天前
Unity引擎界面各个功能面板详细介绍
unity·游戏引擎
℡枫叶℡1 天前
Unity 2D资产命名常用缩写
unity·资产命名缩写
丁小未1 天前
Unity AssetBundle商业化项目资源方案
unity·游戏引擎·assetbundle·unity框架
unityのkiven2 天前
通过 Unity 实现杀戮尖塔2式卡牌系统与机制
unity·游戏引擎
郝学胜-神的一滴2 天前
中级OpenGL教程 020:巧用数组与循环实现多点点光源渲染,告别冗余代码重构方案
c++·unity·游戏引擎·godot·图形渲染·unreal
qq_170264752 天前
unity的锁帧和垂直同步
unity·游戏引擎
承渊政道2 天前
飞算Java炫技赛:Java×Unity数字孪生园区平台的从零落地记录
java·开发语言·unity·技术分享·vibe coding·飞算javaai·飞算java ai炫技赛
unityのkiven2 天前
Unity 共享材质修改问题与 MaterialPropertyBlock 解决方案
unity·游戏引擎·材质
丁小未2 天前
Unity 极致高效的IM设计方案教程
unity·性能优化·游戏引擎·im
unityのkiven2 天前
Unity UGUI 中 EventTrigger 导致 ScrollRect 鼠标滚轮失效的问题分析与解决
unity·计算机外设·游戏引擎