Constraint组件可以约束物体,链接本物体与目标物体的Transform,跟随目标物体的位置、旋转、缩放,实现父子物体一样的效果,却不用设置父子关系。而且一个物体可以同时关联多个目标物体,设置不同的权重
官方文档:Unity - Manual: Constraints
- Aim Constraints: 瞄准目标对象,自动设置物体的旋转
- Look At Constraints: 朝向目标对象,同上
- Parent Constraints: 关联位置与旋转关系,实现父子物体效果
- Position Constraints: 关联位置关系
- Rotation Constraints: 关联旋转关系
- Scale Constraints: 关联缩放关系
以Parent Constraints为例,
- Active:激活组件,并锁定编辑
- Zero:重置组件,并锁定编辑
- Is Active:激活组件
- Weight:组件被影响的权重
- Lock:锁定编辑
- Position At Rest:目标对象权重为0时的位置
- Rotation At Rest:目标对象权重为0时的旋转
- Position Offset:自动移动时的偏移量
- Rotation Offset:自动旋转时的偏移量
- Freeze Position Axes:要冻结的移动轴,冻结的轴向才能关联目标对象自动移动
- Freeze Rotation Axes:要冻结的旋转轴,冻结的轴向才能关联目标对象自动旋转
- Sources:要关联的目标对象,可以有多个,并设置不同的权重
也可以在代码中动态关联或取消关联,动态修改参数设置。
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Animations;
public class MyNewBehaviourScript : MonoBehaviour
{
[SerializeField] Transform targetTrans;
private void Start()
{
ParentConstraint parentConstraint = gameObject.GetComponent<ParentConstraint>();
if (parentConstraint == null)
{
parentConstraint = gameObject.AddComponent<ParentConstraint>();
//设置组件影响权重
parentConstraint.weight = 1;
//目标对象权重为0时的参数
parentConstraint.translationAtRest = Vector3.zero;
parentConstraint.rotationAtRest = Vector3.zero;
//冻结轴向,自动关联目标对象
parentConstraint.translationAxis = Axis.X | Axis.Y | Axis.Z;
parentConstraint.rotationAxis = Axis.X | Axis.Y | Axis.Z;
}
//添加目标对象
ConstraintSource constraintSource = new ConstraintSource() { sourceTransform = targetTrans, weight = 1 };
parentConstraint.SetSources(new List<ConstraintSource>() { constraintSource });
//设置相对偏移量
parentConstraint.SetTranslationOffset(0, Vector3.zero);
parentConstraint.SetRotationOffset(0, Vector3.zero);
//激活组件
parentConstraint.constraintActive = true;
}
public void Stop()
{
ParentConstraint parentConstraint = gameObject.GetComponent<ParentConstraint>();
if (parentConstraint != null)
{
//情况目标
parentConstraint.SetSources(new List<ConstraintSource>());
//取消激活
parentConstraint.constraintActive = false;
}
}
}