赞
踩
功能本身很简单,就是计算初始的 Position offset
和 Rotation offset
时需要注意一下坐标系。示例代码:
public static ParentConstraint SetParentConstraint(Transform target, Transform parentSource, ParentConstraint constraint = null) { Assert.IsTrue(!constraint || target == constraint.transform); if (!constraint) { if (!parentSource) return null; constraint = target.gameObject.AddComponent<ParentConstraint>(); } // 清空已有约束 constraint.constraintActive = false; for (int i = constraint.sourceCount - 1; i >= 0; i--) { constraint.RemoveSource(i); } // 无约束 if (!parentSource) return constraint; // 设置新约束 constraint.AddSource(new ConstraintSource { sourceTransform = parentSource, weight = 1, }); // 设置 Position offset var positionOffset = parentSource.InverseTransformPoint(target.position); constraint.SetTranslationOffset(0, positionOffset); // 设置 Rotation offset var localForward = parentSource.InverseTransformDirection(target.forward); var localUpward = parentSource.InverseTransformDirection(target.up); var rotationOffset = Quaternion.LookRotation(localForward, localUpward).eulerAngles; constraint.SetRotationOffset(0, rotationOffset); // 激活约束 constraint.constraintActive = true; return constraint; }
附带可能用到的坐标系转换方法:
/// <summary> /// 局部坐标转世界坐标。 /// </summary> /// <param name="localPosition">局部坐标系位置。</param> /// <param name="localRotation">局部坐标系旋转。</param> /// <param name="localCoordWorldPosition">局部坐标系原点在世界坐标系中的位置。</param> /// <param name="localCoordWorldRotation">局部坐标系在世界坐标系中的旋转。</param> /// <param name="worldPosition">转换后的世界坐标系位置。</param> /// <param name="worldRotation">转换后的世界坐标系旋转。</param> public static void LocalToWorld(Vector3 localPosition, Quaternion localRotation, Vector3 localCoordWorldPosition, Quaternion localCoordWorldRotation, out Vector3 worldPosition, out Quaternion worldRotation) { var matrix = Matrix4x4.TRS(localCoordWorldPosition, localCoordWorldRotation, Vector3.one); worldPosition = matrix.MultiplyPoint(localPosition); worldRotation = matrix.rotation * localRotation; // scale = localScale; // scale.Scale(matrix.lossyScale); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。