当前位置:   article > 正文

【Unity|备忘】在脚本中动态设置ParentConstraint_parent constraints 头引用

parent constraints 头引用

【Unity|备忘】在脚本中动态设置ParentConstraint

功能本身很简单,就是计算初始的 Position offsetRotation 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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43

附带可能用到的坐标系转换方法:

/// <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);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/127955
推荐阅读
相关标签
  

闽ICP备14008679号