赞
踩
Constraint组件可以约束物体,链接本物体与目标物体的Transform,跟随目标物体的位置、旋转、缩放,实现父子物体一样的效果,却不用设置父子关系。而且一个物体可以同时关联多个目标物体,设置不同的权重
官方文档:Unity - Manual: Constraints
以Parent Constraints为例,
也可以在代码中动态关联或取消关联,动态修改参数设置。
- 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;
- }
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。