需求:
在某一特殊情况下,物体的子物体需要重新设置新的父物体,但还需要跟随原先物体移动。
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;
}
}
原理:
在游戏开始时计算原父物体与子物体的相对矩阵,在原父物体移动时,通过相对矩阵与原原父物体的世界位置,计算子物体的世界位置。
