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

原理:

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

演示:

相关推荐
mxwin1 天前
Unity Shader 预乘 Alpha 完全指南 解决半透明纹理边缘黑边问题,让你的 UI 渲染更干净
unity·游戏引擎
mxwin1 天前
Unity URP 软粒子(Soft Particles)完全指南
unity·游戏引擎·shader
mxwin1 天前
Unity Shader 深度偏移Depth Bias / Offset 完全指南
unity·游戏引擎·shader
星河耀银海1 天前
Unity基础:UI组件详解:Button按钮的点击事件绑定
ui·unity·lucene
RReality1 天前
【Unity Shader URP】平面反射(Planar Reflection)实战教程
ui·平面·unity·游戏引擎·图形渲染·材质
Heikepengmu1 天前
用Unity打造愤怒的小鸟游戏
游戏·unity·游戏引擎
雪儿waii1 天前
Unity 中的 Resources 详解
unity·游戏引擎
RReality2 天前
【Unity UGUI】Toggle / ToggleGroup 与 Dropdown
ui·unity·游戏引擎·图形渲染·材质
雪儿waii2 天前
Unity 中的 InvokeRepeating 详解
unity·游戏引擎
mxwin2 天前
Unity Shader 程序化生成:Shader 中的数学宇宙
unity·游戏引擎