57 lines
1.4 KiB
C#
57 lines
1.4 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEngine.Animations;
|
|
using UnityEngine.Assertions;
|
|
|
|
namespace BITKit
|
|
{
|
|
public static class ConstraintExtensions
|
|
{
|
|
public static ParentConstraint SetParentConstraint(this Transform target, Transform parentSource,
|
|
ParentConstraint constraint = null)
|
|
{
|
|
Assert.IsTrue(!constraint || target == constraint.transform);
|
|
|
|
if (!constraint)
|
|
{
|
|
if (!parentSource) return null;
|
|
constraint = target.gameObject.GetOrAddComponent<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;
|
|
}
|
|
}
|
|
|
|
}
|