【Unity】不用设置父子关系,使用Constraint组件约束物体

本文深入讲解Unity中的Constraint组件,如何通过约束物体实现复杂的动画效果,包括位置、旋转和缩放的关联,以及如何使用代码动态控制这些约束。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
        }
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

萧然CS

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值