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

原理:

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

演示:

相关推荐
Behaviour37 分钟前
Unity游戏HybridCLR 热更新接入实战
游戏·unity·游戏引擎
LONGZETECH14 小时前
新能源汽车动力电池实训教学痛点与虚拟仿真技术解决方案
c语言·3d·unity·架构·汽车·汽车教学软件
王维志14 小时前
UiSplineRenderer
unity·游戏引擎
FairGuard手游加固18 小时前
iOS 游戏加固技术解析:代码混淆、资源加密、内存保护与重签名检测
安全·游戏·macos·unity·ios·objective-c
UWA2 天前
GPM 2.0 WebGL 监测能力扩容|覆盖 Unity/Cocos/LayaAir 多引擎微信 & 抖音小游戏
unity·微信·性能优化·小游戏·webgl
Behaviour2 天前
Unity 手游网络同步技术
网络·unity·c#·游戏引擎
niuniudengdeng2 天前
Unity手游APK去广告实战:华为渠道包反编译、广告拦截与“网络不佳“弹窗修复全记录
unity·游戏引擎
Behaviour2 天前
Unity UI循环列表UIScrollViewContent实现
ui·unity·c#·游戏引擎
_ZHOURUI_H_3 天前
Unity EasyECS:并不是所有字段都适合 SoA,Unity 项目中应该怎样拆数据
游戏·unity·性能优化·架构·游戏引擎
TO_ZRG3 天前
Unity 编辑器之 SettingsProvider、Hierarchy、Project、SearchField
java·unity·编辑器