【Unity】让动画系统支持相对坐标

假如你有一个很简单的动画,并且需要应用到许多物体上
但如果你挂载同一个动画到两个物体上,就会这样:

解决方案

(仅测试过 legacy 动画)

挂载此脚本到物体上:

using System.Collections;using System.Collections.Generic;using UnityEngine;/// <summary>/// 此脚本使得在 Animation 中可以使用相对坐标/// </summary>[RequireComponent(typeof(Animation))]public class RelativePositonForAnimation : MonoBehaviour {    [HideInInspector] public Vector3 positon;    private Vector3 startPosition;void Start ()     {        this.startPosition = this.transform.position;}void Update ()     {        Vector3 newPos = this.startPosition + this.positon;        if(newPos != this.startPosition) //没有在动画中使用此脚本的情况            this.transform.position = newPos;}}

编辑动画时选择Relative Positon For Animation中的Position

改完之后的效果:

加上这个脚本可以方便的显示相对坐标:
(放在 Editor文件夹中)

using System.Collections;using System.Collections.Generic;using UnityEngine;using UnityEditor;[CustomEditor(typeof(RelativePositonForAnimation))]public class RelativePositionInspector : Editor {    private RelativePositonForAnimation instance;    private bool isShowing = false;    private Vector3 startPositon;    private void OnEnable()    {        this.instance = (RelativePositonForAnimation)this.target;    }    public override void OnInspectorGUI()    {        EditorGUILayout.BeginVertical();        EditorGUILayout.LabelField("[Editor]Relative Position: ");        ShowRelativePositon();        if (GUILayout.Button(this.isShowing ? "Hide" : "Show"))        {            this.isShowing = !this.isShowing;            if (this.isShowing)                this.startPositon = instance.transform.position; //获取开始坐标        }        EditorGUILayout.EndVertical();    }    //显示相对坐标    private void ShowRelativePositon()    {        if (this.isShowing)        {            EditorGUILayout.Vector3Field("Position", this.instance.transform.position - this.startPositon);        }    }}

已知缺点:编辑时不能实时预览动画

(0)

相关推荐