//  // add trigger ended event
    //    if (animator != null)
    //    {
    //        AnimationEvent ev = new AnimationEvent();
    //        ev.functionName = "TriggerEnded";
    //        if (animator.runtimeAnimatorController == null)
    //            return;
    //        AnimationClip[] clips = animator.runtimeAnimatorController.animationClips;
    //        if (clips != null)
    //        {
    //            foreach (var clip in clips)
    //            {
    //                if (clip.name == "Trigger")
    //                {
    //                    ev.time = clip.length;
    //                    clip.AddEvent(ev);
    //                    break;
    //                }
    //            }
    //        }
    public static void AddAnimEvent(Animator animator, string clipName, string methodName, int param)
    {
        if (animator.runtimeAnimatorController == null)
            return;

        // find the clip by name
        AnimationClip animClip = null;
        AnimationClip[] clips = animator.runtimeAnimatorController.animationClips;
        if (clips != null) {
            foreach (var clip in clips) {
                if (clip.name == clipName) {
                    animClip = clip;
                    break;
                }
            }
        }

        AnimationEvent ev = new AnimationEvent ();
        ev.functionName = methodName;
        ev.intParameter = param;

        // at the begining
        ev.time = 0;

        animClip.AddEvent (ev);
    }
Exemple #2
0
 void runEvent(AnimationEvent delegateEvent)
 {
     if(delegateEvent != null)
     {
         delegateEvent();
     }
 }
Exemple #3
0
 public void animationEvent(AnimationEvent ae)
 {
     //Debug.Log(a);
     //Debug.Log(b);
     //Debug.Log(s);
     //Debug.Log(sk);
 }
Exemple #4
0
    private static void loadBeetle1Anim(Animation animation)
    {
        //攻击
        AnimationEvent eStrike = new AnimationEvent();
        eStrike.functionName = "OnStrike";
        AnimationEvent eStrikeEnd = new AnimationEvent();
        eStrikeEnd.time = 1.63f;
        eStrikeEnd.functionName = "OnStrikeEnd";
        AnimationClip strikeClip = animation.GetClip("beetle1_strike");
        strikeClip.events = new AnimationEvent[] { eStrike, eStrikeEnd };

        //受击
        AnimationEvent eStriked = new AnimationEvent();
        eStriked.time = 0.66f;
        eStriked.functionName = "OnStrikedEnd";
        AnimationClip strikedClip = animation.GetClip("beetle1_striked");
        strikedClip.events = new AnimationEvent[] { eStriked };

        //死亡
        AnimationEvent eDyingEnd = new AnimationEvent();
        eDyingEnd.time = 1.3f;
        eDyingEnd.functionName = "OnDyingEnd";
        AnimationClip dieClip = animation.GetClip("beetle1_die");
        dieClip.events = new AnimationEvent[] { eDyingEnd };
    }
 void Start()
 {
     //アニメーションイベントを設定
     animEvent = new AnimationEvent();
     animEvent.time = this.gameObject.animation.clip.length;
     animEvent.functionName = "AnimationEventFunction";
     this.gameObject.animation.clip.AddEvent(animEvent);
 }
    // Use this for initialization
    void Start()
    {
        anim = GetComponent<Animation> ();

        AnimationEvent actionEvent = new AnimationEvent ();
        actionEvent.functionName = "AttackStart";
        actionEvent.messageOptions = SendMessageOptions.DontRequireReceiver;
        actionEvent.time = 12f / 30f;
        anim["Attack"].clip.AddEvent(actionEvent);
    }
    public static void AddAnimEvent(Animator animator, AnimationClip clip, string methodName, Object param)
    {
        AnimationEvent ev = new AnimationEvent ();
        ev.functionName = methodName;
        ev.objectReferenceParameter = param;

        // at the begining
        ev.time = 0;

        clip.AddEvent (ev);
    }
Exemple #8
0
 public void PlayFootstep(AnimationEvent animationEvent)
 {
     if (animationEvent.floatParameter == activeLayer && animationEvent.animatorClipInfo.weight > 0.5f)
     {
         _audioSource.PlayOneShot(_currentClips[_currentIndices[_currentIndex]]);
         _currentIndex++;
         if (_currentIndex >= _currentIndices.Count)
         {
             _currentIndex = Random.Range(0, _currentIndices.Count);
         }
     }
 }
    //设置动作时间
    public void animationClipEvent( AID aid, AnimationEvent ae )
    {
        IBaseAnimation am = getAnimation( aid );

        if ( am != null )
        {
            am.setAnimationEvent( _animation, ae );
        }
        else
        {
            Debug.Log( "Function: animationClipEvent --  the player '" + _playerName + "' didn't have animation " + aid.id );
        }
    }
    void Start()
    {
        if (stateWhenStart.Length > 0)
            toAnimationState(stateWhenStart);

        foreach (unityAniStateConfigInfo lStateConfigInfo in animationConfig)
        {
            //是否使用配置
            if(lStateConfigInfo.useTheConfig)
            {
                AnimationState lAnimationState = myAnimation[lStateConfigInfo.animationName];
                lAnimationState.speed = lStateConfigInfo.speed;
                lAnimationState.layer = lStateConfigInfo.layer;
                foreach (var lTransform in lStateConfigInfo.MixingTransforms)
                {
                    lAnimationState.AddMixingTransform(lTransform);
                }

                AnimationClip   lAnimationClip = lAnimationState.clip;
                if (!haveAddedEvent.ContainsKey(lAnimationClip))
                {
                    //创建事件
                    foreach (unityAniEventInfo lEventInfo in lStateConfigInfo.events)
                    {
                        AnimationEvent lAnimationEvent = new AnimationEvent();
                        lAnimationEvent.functionName = lEventInfo.functionName;
                        lAnimationEvent.stringParameter = lEventInfo.stringParameter;
                        float lEventTime;
                        if (lEventInfo.overEnd)
                        {
                            lEventTime = lAnimationClip.length - 0.01f;
                        }
                        else
                        {
                            lEventTime = lEventInfo.time;
                        }
                        lAnimationEvent.time = lEventTime;
                        lAnimationClip.AddEvent(lAnimationEvent);
                    }
                    haveAddedEvent[lAnimationClip] = true;

                }
                //else
                //{
                //    Debug.Log("haveAddedEvent.ContainsKey(lAnimationClip)");
                //}
            }
        }
    }
Exemple #11
0
    void onPlayerMovement(AnimationEvent ev)
    {
        state = ev.State;

        switch (state)
        {
            case AnimationEvent.Land:
                target.CrossFade("Land");
                break;

            case AnimationEvent.Jump:
                target.CrossFade("Jump");
                break;
        }
    }
Exemple #12
0
    protected void releaseSlug(AnimationEvent e)
    {
        var newSlug = (GameObject)Instantiate(slug);

        newSlug.transform.parent = slugPosition;
        newSlug.transform.localPosition = offset;
        newSlug.transform.localRotation = Quaternion.identity;
        newSlug.transform.parent = null;
        var slugRigid = newSlug.AddComponent<Rigidbody>();

        slugRigid.AddForce(newSlug.transform.right * ejectForce, ForceMode.VelocityChange);
        slugRigid.AddTorque(Random.insideUnitSphere);

        Destroy(newSlug, 10);
    }
Exemple #13
0
 void Start()
 {
     knightObject = GameObject.FindGameObjectWithTag ("Player");
     if (knightObject != null) {
         target = knightObject.transform;
         knight = knightObject.GetComponent<Knight> ();
     }
     AnimationEvent hitEvent = new AnimationEvent();
     hitEvent.functionName = "SetIdle";
     hitEvent.time = animation.GetClip("gethit").length;
     animation.GetClip("gethit").AddEvent(hitEvent);
     AnimationEvent attackEvent = new AnimationEvent();
     attackEvent.functionName = "SetIdle";
     attackEvent.time = animation.GetClip("attack").length;
     animation.GetClip("attack").AddEvent(attackEvent);
 }
    public void OnAttackStarted( AnimationEvent animationEvent )
    {
        if( MovementModel != null )
        {
            MovementModel.OnAttackStarted();
        }

        if( MovementView != null )
        {
            MovementView.OnAttackStarted();
        }

        ShowWeapon();
        SetSortingOrderOfWeapon( animationEvent.intParameter );
        SetShieldDirection( animationEvent.stringParameter );
    }
Exemple #15
0
    private static void loadFlower1Anim(Animation animation)
    {
        //攻击
        AnimationEvent eStrikeEnd = new AnimationEvent();
        eStrikeEnd.time = 1.8f;
        eStrikeEnd.functionName = "OnStrikeEnd";
        AnimationClip strikeClip = animation.GetClip("flower1_strike");
        strikeClip.events = new AnimationEvent[] { eStrikeEnd };

        //死亡
        AnimationEvent eDyingEnd = new AnimationEvent();
        eDyingEnd.time = 1.7f;
        eDyingEnd.functionName = "OnDyingEnd";
        AnimationClip dieClip = animation.GetClip("flower1_die");
        dieClip.events = new AnimationEvent[] { eDyingEnd };
    }
    void SubscribeToAnimation()
    {
        AnimationEvent startBubbles = new AnimationEvent();
        startBubbles.time = 0.01f;
        startBubbles.functionName= "StartBubbles";
        animation["Shot"].clip.AddEvent(startBubbles);

        AnimationEvent stopBubbles = new AnimationEvent();
        stopBubbles.time = 0.45f;
        stopBubbles.functionName= "StopBubbles";
        animation["Shot"].clip.AddEvent(stopBubbles);

        AnimationEvent stopBubblesNow = new AnimationEvent();
        stopBubblesNow.time = 0.01f;
        stopBubblesNow.functionName= "StopBubbles";
        animation["Reload"].clip.AddEvent(stopBubblesNow);
    }
    // OnStateEnter is called before OnStateEnter is called on any state inside this state machine
    public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        Debug.Log(1 + "-" + stateInfo.fullPathHash + "-" + Animator.StringToHash("Base.Idle.idle1")+"-"+ stateInfo.length + "-" + stateInfo.normalizedTime + "-" + (stateInfo.normalizedTime - prev));
        prev = stateInfo.normalizedTime;

        //  animationManager.initState(animator, stateInfo);
        AnimationEvent ae = new AnimationEvent();
        ae.functionName = "animationEvent";

        AnimatorTransitionInfo ati = animator.GetAnimatorTransitionInfo(layerIndex);

        AnimatorClipInfo aci = animator.GetCurrentAnimatorClipInfo(layerIndex)[0];
        aci.clip.AddEvent(ae);
        Debug.Log( "进入:"+ aci.clip.name +"-"+ stateInfo.fullPathHash + "-" + stateInfo.length + "-" + stateInfo.normalizedTime + "-" + (stateInfo.normalizedTime - prev));
        //animator.SetInteger("idle",Random.Range(1, 3));
        //AnimationAction animationAction = AnimationManager.getAnimationAction(animator);
    }
Exemple #18
0
    void OnAnimationEvent(AnimationEvent evt)
    {
        Debug.Log("=============>>  OnAnimationEvent, curr Time = " + Time.realtimeSinceStartup.ToString());
        animation.Stop(clip1.name);
        //animation.Play(clip2.name);

        if(!addevent)
        {
            AnimationEvent evvt = new AnimationEvent();
            evvt.time = 3f;
            evvt.functionName = "OnAnimationEvent";
            evvt.messageOptions = SendMessageOptions.DontRequireReceiver;
            animation[clip1.name].clip.AddEvent(evt);
            animation.Play(clip1.name);
            addevent = true;
        }
    }
Exemple #19
0
    /// <summary>
    /// 注册无参事件
    /// </summary>
    /// <param name="clip">动画片</param>
    /// <param name="time">事件</param>
    /// <param name="onAnimEvent">回调</param>
    public void AddAnimEvent(AnimationClip clip, float time, System.Action onAnimEvent)
    {
        AnimationEvent animEvent = new AnimationEvent();
        //固定一个事件方法,就不需要对每个事件都写一个
        animEvent.functionName = "OnAnimEvent";
        animEvent.time = time;
        animEvent.messageOptions = SendMessageOptions.RequireReceiver;
        //用hash码记录是哪一个回调函数,还没想到更好的方法
        animEvent.intParameter = onAnimEvent.GetHashCode();

        if (!onAnimEventDic.ContainsKey(animEvent.intParameter))
        {
            onAnimEventDic.Add(animEvent.intParameter, onAnimEvent);
        }

        clip.AddEvent(animEvent);
    }
Exemple #20
0
    void Start()
    {
        if(null != animation)
        {
            animation.AddClip(clip1, clip1.name);
            animation.AddClip(clip2, clip1.name);

            animation.wrapMode = WrapMode.Loop;
            //animation.clip = clip1;

            AnimationEvent evt = new AnimationEvent();
            evt.time = 1f;
            evt.functionName = "OnAnimationEvent";
            evt.messageOptions = SendMessageOptions.DontRequireReceiver;
            animation[clip1.name].clip.AddEvent(evt);
            animation.Play(clip1.name);
        }
    }
Exemple #21
0
    public void CrossFadeTargetEvent(AnimationEvent animationEvent)
    {
        if (animationEvent == null) return;
        var anim = theTarget.animation;
        if (anim != null)
        {
            if (dodgeOrHit == 0)
            {

                anim.CrossFade(AnimationResources.Dodge);
                anim.CrossFadeQueued(AnimationResources.Freeze);
            }
            else
            {
                anim.CrossFade(AnimationResources.Flinch);
                anim.CrossFadeQueued(AnimationResources.Freeze);
            }
        }
    }
Exemple #22
0
    public void AddAnimEvent(object obj, AnimationClip clip, float time, System.Action<object> onAnimEventObj)
    {
        AnimationEvent animEvent = new AnimationEvent();
        animEvent.functionName = "OnAnimEventParam";
        animEvent.time = time;
        animEvent.messageOptions = SendMessageOptions.RequireReceiver;
        //用hash码记录回调函数
        animEvent.intParameter = onAnimEventObj.GetHashCode();

        if (!onAnimEventObjDic.ContainsKey(animEvent.intParameter))
        {
            onAnimEventObjDic.Add(animEvent.intParameter, onAnimEventObj);
        }
        if (!paramDic.ContainsKey(animEvent.intParameter))
        {
            paramDic.Add(animEvent.intParameter, obj);
        }

        clip.AddEvent(animEvent);
    }
    void AddEvent()
    {
        AnimationEvent e = new AnimationEvent();

        foreach (AnimEvent ae in animEvent)
        {
            e.functionName = "PlaySFX";
            e.objectReferenceParameter = ae.sfx;

            for (int i = 0; i < ae.frames.Length; i++)
            {
				try{
                e.time = ae.frames[i];
                GetComponent<Animation>()[ae.animationName].clip.AddEvent(e);
				}catch(NullReferenceException){
					Debug.Log("AnimationEventBasedSound.cs: Can't find " + ae.animationName);
				}
            }
        }
    }
    //增加动画事件
    public void AddEvent(BaseActor baseActor, string animationName, EEventType eventType)
    {
        switch (eventType)
        {
            case EEventType.SwapGun:
                {
                    IAction act = ScriptableObject.CreateInstance<IAction>();
                    act.name = EEventType.SwapGun.ToString();
                    act.eventType = (int)EEventType.SwapGun;
                    act.baseActor = baseActor;

                    AnimationEvent evt = new AnimationEvent();                    
                    evt.time = 0.5f;
                    evt.functionName = "OnAnimationEvent";
                    evt.objectReferenceParameter = act as Object;
                    animation.GetClip(animationName).AddEvent(evt);
                }
                break;
            default:
                break;
        }
    }
Exemple #25
0
 //Use string paramater for name and int paramater for value (1 for true, 0 for false)
 public void setBool(AnimationEvent values)
 {
     animator.SetBool(values.stringParameter, values.intParameter > 0);
 }
 public virtual void Event_ActivateEffect(AnimationEvent animEvent)
 {
     Event_ActivateFx(animEvent);
 }
Exemple #27
0
 private void OnAllImmune(AnimationEvent e)
 {
     this.SetFrameRate(1f, true);
     this.OnlyKilledBySuicide = true;
     base.get_transform().set_parent(FXPool.Instance.root.get_transform());
 }
Exemple #28
0
 public void test(AnimationEvent t)
 {
     Debug.Log("EVENT" + t.objectReferenceParameter.name);
 }
        public static void OnEditAnimationEvents(AnimationWindowEvent[] awEvents)
        {
            AnimationWindowEventData data = GetData(awEvents);
            if (data.events == null || data.selectedEvents == null || data.selectedEvents.Length == 0)
                return;

            AnimationEvent firstEvent = data.selectedEvents[0];

            bool singleFunctionName = Array.TrueForAll(data.selectedEvents, evt => evt.functionName == firstEvent.functionName);

            GUI.changed = false;

            if (data.root != null)
            {
                List<AnimationWindowEventMethod> methods = new List<AnimationWindowEventMethod>();
                HashSet<string> overloads = new HashSet<string>();
                CollectSupportedMethods(data.root, methods, overloads);

                var methodsFormatted = new List<string>(methods.Count);

                for (int i = 0; i < methods.Count; ++i)
                {
                    AnimationWindowEventMethod method = methods[i];

                    string postFix = " ( )";
                    if (method.parameterType != null)
                    {
                        if (method.parameterType == typeof(float))
                            postFix = " ( float )";
                        else if (method.parameterType == typeof(int))
                            postFix = " ( int )";
                        else
                            postFix = string.Format(" ( {0} )", method.parameterType.Name);
                    }

                    methodsFormatted.Add(method.name + postFix);
                }

                int notSupportedIndex = methods.Count;
                int selected = methods.FindIndex(method => method.name == firstEvent.functionName);
                if (selected == -1)
                {
                    selected = methods.Count;

                    AnimationWindowEventMethod newMethod = new AnimationWindowEventMethod();
                    newMethod.name = firstEvent.functionName;
                    newMethod.parameterType = null;

                    methods.Add(newMethod);

                    if (string.IsNullOrEmpty(firstEvent.functionName))
                        methodsFormatted.Add(kNoneSelected);
                    else
                        methodsFormatted.Add(firstEvent.functionName + kNotSupportedPostFix);
                }

                EditorGUIUtility.labelWidth = 130;

                EditorGUI.showMixedValue = !singleFunctionName;
                int wasSelected = singleFunctionName ? selected : -1;
                selected = EditorGUILayout.Popup("Function: ", selected, methodsFormatted.ToArray());
                if (wasSelected != selected && selected != -1 && selected != notSupportedIndex)
                {
                    foreach (var evt in data.selectedEvents)
                    {
                        evt.functionName = methods[selected].name;
                        evt.stringParameter = string.Empty;
                    }
                }
                EditorGUI.showMixedValue = false;

                var selectedParameter = methods[selected].parameterType;

                if (singleFunctionName && selectedParameter != null)
                {
                    EditorGUILayout.Space();
                    if (selectedParameter == typeof(AnimationEvent))
                        EditorGUILayout.PrefixLabel("Event Data");
                    else
                        EditorGUILayout.PrefixLabel("Parameters");

                    DoEditRegularParameters(data.selectedEvents, selectedParameter);
                }

                if (overloads.Count > 0)
                {
                    EditorGUILayout.Space();
                    EditorGUILayout.HelpBox(s_OverloadWarning.text, MessageType.Warning, true);
                }
            }
            else
            {
                EditorGUI.showMixedValue = !singleFunctionName;
                string oldFunctionName = singleFunctionName ? firstEvent.functionName : "";
                string functionName = EditorGUILayout.TextField(EditorGUIUtility.TrTextContent("Function"), oldFunctionName).Replace(" ", "");
                if (functionName != oldFunctionName)
                {
                    foreach (var evt in data.selectedEvents)
                    {
                        evt.functionName = functionName;
                        evt.stringParameter = string.Empty;
                    }
                }
                EditorGUI.showMixedValue = false;

                if (singleFunctionName)
                {
                    DoEditRegularParameters(data.selectedEvents, typeof(AnimationEvent));
                }
                else
                {
                    using (new EditorGUI.DisabledScope(true))
                    {
                        AnimationEvent dummyEvent = new AnimationEvent();
                        DoEditRegularParameters(new AnimationEvent[] {dummyEvent}, typeof(AnimationEvent));
                    }
                }
            }

            if (GUI.changed)
                SetData(awEvents, data);
        }
        private static string FormatEventArguments(IEnumerable <Type> paramTypes, AnimationEvent evt)
        {
            string result;

            if (!paramTypes.Any <Type>())
            {
                result = " ( )";
            }
            else if (paramTypes.Count <Type>() > 1)
            {
                result = " (Function Not Supported)";
            }
            else
            {
                Type type = paramTypes.First <Type>();
                if (type == typeof(string))
                {
                    result = " ( \"" + evt.stringParameter + "\" )";
                }
                else if (type == typeof(float))
                {
                    result = " ( " + evt.floatParameter + " )";
                }
                else if (type == typeof(int))
                {
                    result = " ( " + evt.intParameter + " )";
                }
                else if (type.IsEnum)
                {
                    result = string.Concat(new string[]
                    {
                        " ( ",
                        type.Name,
                        ".",
                        Enum.GetName(type, evt.intParameter),
                        " )"
                    });
                }
                else if (type == typeof(AnimationEvent))
                {
                    result = string.Concat(new object[]
                    {
                        " ( ",
                        evt.floatParameter,
                        " / ",
                        evt.intParameter,
                        " / \"",
                        evt.stringParameter,
                        "\" / ",
                        (!(evt.objectReferenceParameter == null)) ? evt.objectReferenceParameter.name : "null",
                        " )"
                    });
                }
                else if (type.IsSubclassOf(typeof(UnityEngine.Object)) || type == typeof(UnityEngine.Object))
                {
                    result = " ( " + ((!(evt.objectReferenceParameter == null)) ? evt.objectReferenceParameter.name : "null") + " )";
                }
                else
                {
                    result = " (Function Not Supported)";
                }
            }
            return(result);
        }
 public virtual void Event_MoveFxToOpponent(AnimationEvent animEvent)
 {
 }
Exemple #32
0
    /// <summary>
    /// Equipment sounds
    /// Triggered once in the walk cycle when weapon is on the back
    /// </summary>
    /// <param name="evt"></param>
	public void FootSword(AnimationEvent evt)
    {
        if (!is_weapon_equiped)
        {
            if (evt.animatorClipInfo.weight > 0.5 && evt.intParameter == a.GetDominantLayer())
            {
                int rnd = Random.Range(0, 3);
                if (evt.intParameter == 1) rnd = Random.Range(0, 1);
                switch (rnd)
                {
                    case 0:
                        AudioSource.PlayClipAtPoint(Sounds.SwordWalk1, transform.position, Settings.SoundVolume);
                        break;
                    case 1:
                        AudioSource.PlayClipAtPoint(Sounds.SwordWalk2, transform.position, Settings.SoundVolume);
                        break;
                }
            }
        }
    }
Exemple #33
0
    public void SlideAnim(List<Keyframe> frameList)
    {
        Frames = frameList;
        AnimationCurve curve = new AnimationCurve(Frames.ToArray());
        AnimationClip clip = new AnimationClip();

        clip.SetCurve("", typeof(RemoteGUI), "GuiAlpha", curve);
        clip.SetCurve("", typeof(RemoteGUI), "GuiAlpha", curve);
        Animation.AddClip(clip, "test");
        Animation.Play("test");
        AnimationEvent endEvent = new AnimationEvent();
        endEvent.time = clip.length;
        endEvent.functionName = "TransitionEnd";
        Animation["test"].clip.AddEvent(endEvent);
    }
Exemple #34
0
        private void ParseAnimation(String name, Dictionary <String, Object> map)
        {
            bool isNewClip = false;

            AnimationClip clip = GetAndClearAnimationClip(name, ref isNewClip);

            if (map.ContainsKey("bones"))
            {
                foreach (KeyValuePair <String, Object> entry in (Dictionary <String, Object>)map["bones"])
                {
                    String boneName = entry.Key;

                    Transform bone = FindChildRecursive(_skeleton, boneName);

                    ParseBoneTimelines(clip, bone, (Dictionary <String, Object>)entry.Value);
                }
            }

            if (map.ContainsKey("slots"))
            {
                foreach (KeyValuePair <String, Object> entry in (Dictionary <String, Object>)map["slots"])
                {
                    String slotName = entry.Key;

                    Transform slot = FindChildRecursive(_skeleton, slotName + " [slot]");

                    ParseSlotTimelines(clip, slotName, slot, (Dictionary <String, Object>)entry.Value);
                }
            }

            if (map.ContainsKey("events"))
            {
                var eventsMap = (List <Object>)map["events"];

                List <AnimationEvent> animationEvents = new List <AnimationEvent>();

                foreach (Dictionary <String, Object> eventMap in eventsMap)
                {
                    string eventName = (string)eventMap["name"];

                    SpineEvent spineEvent = GetEvent(eventName);
                    if (spineEvent == null)
                    {
                        continue;
                    }

                    AnimationEvent animationEvent = new AnimationEvent();
                    animationEvent.time            = (float)eventMap["time"];
                    animationEvent.functionName    = eventName;
                    animationEvent.intParameter    = GetInt(eventMap, "int", spineEvent.IntParameter);
                    animationEvent.floatParameter  = GetFloat(eventMap, "float", spineEvent.FloatParameter);
                    animationEvent.stringParameter = GetString(eventMap, "string", spineEvent.StringParameter);

                    animationEvents.Add(animationEvent);
                }

                AnimationUtility.SetAnimationEvents(clip, animationEvents.ToArray());
            }

            UpdateClipSettings(clip, isNewClip);
        }
Exemple #35
0
    private static void createCilp(string objName, string objPath, string eventPath, List <animClip> clips)
    {
        string path          = objPath + ".FBX";
        var    modelImporter = AssetImporter.GetAtPath(path) as ModelImporter;

        if (modelImporter == null)
        {
            return;
        }
        string savePath = getAnimPathByName(objName, "clip");

        //帧事件信息
        Dictionary <string, animEventTotal> events = new Dictionary <string, animEventTotal>();

        getEvent(eventPath, ref events);

        modelImporter.animationType      = ModelImporterAnimationType.Generic;
        modelImporter.importAnimation    = true;
        modelImporter.generateAnimations = ModelImporterGenerateAnimations.GenerateAnimations;
        ModelImporterClipAnimation[] animations = new ModelImporterClipAnimation[clips.Count];
        for (int i = 0; i < clips.Count; i++)
        {
            ModelImporterClipAnimation tempClip = new ModelImporterClipAnimation();
            tempClip.name       = clips[i].clipName;
            tempClip.firstFrame = clips[i].startIndex;
            tempClip.lastFrame  = clips[i].endIndex;
            tempClip.loopTime   = clips[i].isLoop;
            tempClip.wrapMode   = clips[i].isLoop ? WrapMode.Loop : WrapMode.Default;
            tempClip.loopPose   = true;
            if (events.ContainsKey(tempClip.name))
            {
                animEventTotal   total      = events[tempClip.name];
                AnimationEvent[] clipEvents = new AnimationEvent[total.eventLst.Count];
                for (int k = 0; k < total.eventLst.Count; k++)
                {
                    AnimationEvent ae = new AnimationEvent();
                    ae.functionName    = total.eventLst[k].eventName;
                    ae.stringParameter = total.eventLst[k].args;
                    ae.time            = total.eventLst[k].frame;
                    clipEvents[k]      = ae;
                }
                tempClip.events = clipEvents;
            }
            animations[i] = tempClip;
        }
        modelImporter.clipAnimations = animations;

        UnityEngine.Object[] objs = AssetDatabase.LoadAllAssetsAtPath(path);
        for (int i = 0; i < objs.Length; i++)
        {
            if (objs[i] is AnimationClip && !objs[i].name.StartsWith("_"))
            {
                AnimationClip old     = objs[i] as AnimationClip;
                AnimationClip newClip = new AnimationClip();
                EditorUtility.CopySerialized(old, newClip);
                AssetDatabase.CreateAsset(newClip, Path.Combine(savePath, newClip.name + ".anim"));
            }
        }
        AssetDatabase.ImportAsset(modelImporter.assetPath);
        AssetDatabase.Refresh();
    }
Exemple #36
0
        /**
         * @brief Stores the current clip into a Unity .anim file
         * Important: If you use your own character with blend shapes, you have to make sure it is
         * set to 'legacy' animation type. You can do this by the following steps in Unity3D:
         * 1. In the 'project' window in the Assets hierarchy, click on your fbx model
         * 2. In the Inspector, you should see now the Import Settings of your model.
         * 3. Select in these Import Settings in the 'Rig' tab for the 'Animation Type' the value 'Legacy'
         */
        public AnimationClip GetClipAsAnim(string path)
        {
            bool have_t_pose = false;

            if (m_TPose != null && m_TPose.m_joints != null)
            {
                if (m_TPose.m_joints.Count != m_GameObjectTransformations.Count)
                {
                    Debug.LogError("tpose and model do not have the same number of transformations (" + m_TPose.m_joints.Count + "!="
                                   + m_GameObjectTransformations.Count + ")");
                    return(null);
                }
                have_t_pose = true;
            }
            else
            {
                Debug.LogWarning("tpose missing");
            }

            AnimationClip animation_clip = new AnimationClip();

            // Not all of them might actually be used, since not all of them might be a target
            AnimationCurve [] translation_x_curves = new AnimationCurve[m_GameObjectTransformations.Count];
            AnimationCurve [] translation_y_curves = new AnimationCurve[m_GameObjectTransformations.Count];
            AnimationCurve [] translation_z_curves = new AnimationCurve[m_GameObjectTransformations.Count];
            AnimationCurve [] rotation_x_curves    = new AnimationCurve[m_GameObjectTransformations.Count];
            AnimationCurve [] rotation_y_curves    = new AnimationCurve[m_GameObjectTransformations.Count];
            AnimationCurve [] rotation_z_curves    = new AnimationCurve[m_GameObjectTransformations.Count];
            AnimationCurve [] rotation_w_curves    = new AnimationCurve[m_GameObjectTransformations.Count];
            AnimationCurve [] bs_curves            = new AnimationCurve[m_GameObjectBlendshapes.Count];

            Clip clip = m_clip.Duplicate();

            if (m_normalize_headpose)
            {
                clip.NormalizeHeadPoseAllClip();
            }

            Debug.Log("nr of clip states: " + clip.NumStates());
            for (int frame_nr = 0; frame_nr < clip.NumStates(); frame_nr++)
            {
                if (!clip[frame_nr].TrackingSuccessful())
                {
                    Debug.Log("skipping clip state");
                    continue;
                }

                // get frame time
                float time = (float)(clip[frame_nr].Timestamp() - clip[0].Timestamp()) * 0.001f;                 // time is in ms

                // evaluate transformation
                TransformationValue [] transformation_values = null;
                if (have_t_pose)
                {
                    transformation_values = Utils.EvaluateTargetTransformations(m_Retargeting, clip.Rig(), clip[frame_nr], m_TPose.m_joints);
                }
                else
                {
                    transformation_values = Utils.EvaluateTargetTransformations(m_Retargeting, clip.Rig(), clip[frame_nr], m_GameObjectTransformations);
                }

                int key_index = -1;
                if (transformation_values.Length == m_GameObjectTransformations.Count)
                {
                    for (int index = 0; index < transformation_values.Length; index++)
                    {
                        // Apply the value for this target
                        if (transformation_values[index] != null)
                        {
                            // Apply the translation value for this target
                            if (translation_x_curves[index] == null)
                            {
                                translation_x_curves[index] = new AnimationCurve();
                                translation_y_curves[index] = new AnimationCurve();
                                translation_z_curves[index] = new AnimationCurve();
                            }
                            key_index = translation_x_curves[index].AddKey(time, transformation_values[index].m_translation.x);
                            if (key_index < 0)
                            {
                                Debug.LogError("Could not add key at time " + time);
                            }
                            key_index = translation_y_curves[index].AddKey(time, transformation_values[index].m_translation.y);
                            if (key_index < 0)
                            {
                                Debug.LogError("Could not add key at time " + time);
                            }
                            key_index = translation_z_curves[index].AddKey(time, transformation_values[index].m_translation.z);
                            if (key_index < 0)
                            {
                                Debug.LogError("Could not add key at time " + time);
                            }

                            if (rotation_x_curves[index] == null)
                            {
                                rotation_x_curves[index] = new AnimationCurve();
                                rotation_y_curves[index] = new AnimationCurve();
                                rotation_z_curves[index] = new AnimationCurve();
                                rotation_w_curves[index] = new AnimationCurve();
                            }
                            // Add to curve for the animation
                            key_index = rotation_x_curves[index].AddKey(time, transformation_values[index].m_rotation.x);
                            if (key_index < 0)
                            {
                                Debug.LogError("Could not add key at time " + time);
                            }
                            key_index = rotation_y_curves[index].AddKey(time, transformation_values[index].m_rotation.y);
                            if (key_index < 0)
                            {
                                Debug.LogError("Could not add key at time " + time);
                            }
                            key_index = rotation_z_curves[index].AddKey(time, transformation_values[index].m_rotation.z);
                            if (key_index < 0)
                            {
                                Debug.LogError("Could not add key at time " + time);
                            }
                            key_index = rotation_w_curves[index].AddKey(time, transformation_values[index].m_rotation.w);
                            if (key_index < 0)
                            {
                                Debug.LogError("Could not add key at time " + time);
                            }
                        }
                    }
                }
                else
                {
                    Debug.LogError("Cannot create transformation as evaluated shape size is incorrect");
                }

                // evaluate blendshapes
                BlendshapeValue [] blendshape_values = Utils.EvaluateTargetBlendshapes(m_Retargeting, clip.Rig(), clip[frame_nr], m_GameObjectBlendshapes);

                if (blendshape_values.Length == m_GameObjectBlendshapes.Count)
                {
                    for (int index = 0; index < m_GameObjectBlendshapes.Count; index++)
                    {
                        // Apply the value for this target
                        if (blendshape_values[index] != null)
                        {
                            if (bs_curves[index] == null)
                            {
                                bs_curves[index] = new AnimationCurve();
                            }
                            bs_curves[index].AddKey(time, (float)blendshape_values[index].m_value);
                        }
                    }
                }
                else
                {
                    Debug.LogError("Cannot create blendshapes as evaluated shape size is incorrect");
                }
            }

            // Set all transformation curves for all transformations that are animated
            for (int target_nr = 0; target_nr < m_GameObjectTransformations.Count; target_nr++)
            {
                // Extract path:
                string path_to_transformation = ((TransformationInformation)m_GameObjectTransformations[target_nr]).transformPath;
                // Apply translation curve, if there is one
                if (translation_x_curves[target_nr] != null)
                {
                    animation_clip.SetCurve(path_to_transformation, typeof(Transform), "localPosition.x", translation_x_curves[target_nr]);
                    animation_clip.SetCurve(path_to_transformation, typeof(Transform), "localPosition.y", translation_y_curves[target_nr]);
                    animation_clip.SetCurve(path_to_transformation, typeof(Transform), "localPosition.z", translation_z_curves[target_nr]);
                }
                // Apply rotation curve, if there is one
                if (rotation_x_curves[target_nr] != null)
                {
                    animation_clip.SetCurve(path_to_transformation, typeof(Transform), "localRotation.x", rotation_x_curves[target_nr]);
                    animation_clip.SetCurve(path_to_transformation, typeof(Transform), "localRotation.y", rotation_y_curves[target_nr]);
                    animation_clip.SetCurve(path_to_transformation, typeof(Transform), "localRotation.z", rotation_z_curves[target_nr]);
                    animation_clip.SetCurve(path_to_transformation, typeof(Transform), "localRotation.w", rotation_w_curves[target_nr]);
                }
            }

            // Without this, there are some weird jumps (rotation) in the animation:
            animation_clip.EnsureQuaternionContinuity();

            // Set all blendshape curves for all blendshapes that are animated
            for (int i = 0; i < m_GameObjectBlendshapes.Count; i++)
            {
                if (bs_curves[i] != null)
                {
                    BlendshapeInfo bs_info = (BlendshapeInfo)(m_GameObjectBlendshapes[i]);
                    // Debug.Log("bs_curves[" + i + "].length=" + bs_curves[i].length);
                    string bs_path = bs_info.m_path;
                    string bs_name = bs_info.m_name;
                    animation_clip.SetCurve(bs_path, typeof(SkinnedMeshRenderer), "blendShape." + bs_name, bs_curves[i]);
                }
            }

            Debug.Log("Animation clip = " + animation_clip.length);

            // animation clip asset
            string animation_name = Path.GetFileNameWithoutExtension(path);

            animation_clip.name = animation_name;
            AnimationEvent animation_event = new AnimationEvent();

            animation_event.functionName = "AnimationClipEventCallback";
            animation_event.time         = animation_clip.length;
                        #if UNITY_EDITOR
            AnimationEvent[] animation_events = { animation_event };
            AnimationUtility.SetAnimationEvents(animation_clip, animation_events);
            AssetDatabase.CreateAsset(animation_clip, path);
                        #endif

            Debug.Log("Wrote animation with length " + (1000.0 * animation_clip.length) + " milliseconds");
            return(animation_clip);
        }
        /// <summary>
        /// 模型导入预处理
        /// </summary>
        void OnPreprocessModel()
        {
            string project_relative_path = this.assetPath;
            string folder         = BaseHelp.GetParentDir(project_relative_path);
            string clip_file_path = string.Format("{0}/MecanimConfig.asset", folder);

            // 如果目录下包含MecanimConfig配置,才进行预处理
            MecanimConfig config = AssetDatabase.LoadAssetAtPath(clip_file_path, typeof(MecanimConfig)) as MecanimConfig;

            if (!config)
            {
                return;
            }

            ModelImporter importer = (ModelImporter)this.assetImporter;

            // 默认不导入材质
            importer.importMaterials      = false;
            importer.importBlendShapes    = false;
            importer.isReadable           = false;
            importer.optimizeMeshPolygons = true;
            importer.optimizeMeshVertices = true;
            importer.weldVertices         = true;
            importer.swapUVChannels       = false;
            importer.generateSecondaryUV  = false;
            // 设置旋转校正为0,避免一定程度的抖动
            importer.animationRotationError = 0;

            // 覆盖默认配置
            importer.isReadable = config.enable_read_write;

            List <ModelImporterClipAnimation> reset_list = new List <ModelImporterClipAnimation>();
            int clip_count = config.clips.Count;

            for (int i = 0; i < clip_count; ++i)
            {
                MecanimClipConfig          clip_config = config.clips[i];
                ModelImporterClipAnimation reset       = new ModelImporterClipAnimation();
                reset.name       = clip_config.name;
                reset.firstFrame = clip_config.start_frame;
                reset.lastFrame  = clip_config.end_frame;
                reset.loopTime   = clip_config.loop;
                reset.wrapMode   = clip_config.loop ? WrapMode.Loop : WrapMode.Default;

                // 事件
                List <AnimationEvent> evts = new List <AnimationEvent>();
                int evt_count = clip_config.evts.Count;
                for (int j = 0; j < evt_count; ++j)
                {
                    MecanimClipEvent mecanim_evt = clip_config.evts[j];
                    AnimationEvent   evt         = new AnimationEvent();
                    evt.time = mecanim_evt.time;
                    // 枚举即是函数名称
                    evt.functionName    = mecanim_evt.evt_type.ToString();
                    evt.stringParameter = mecanim_evt.str_param;
                    evt.intParameter    = mecanim_evt.int_param;
                    evts.Add(evt);
                }
                reset.events = evts.ToArray();

                reset_list.Add(reset);
            }

            // 重新赋值
            importer.clipAnimations = reset_list.ToArray();
        }
        private static int InsertAnimationEvent(ref AnimationEvent[] events, AnimationClip clip, AnimationEvent evt)
        {
            Undo.RegisterCompleteObjectUndo(clip, "Add Event");
            int num = events.Length;

            for (int i = 0; i < events.Length; i++)
            {
                if (events[i].time > evt.time)
                {
                    num = i;
                    break;
                }
            }
            ArrayUtility.Insert <AnimationEvent>(ref events, num, evt);
            AnimationUtility.SetAnimationEvents(clip, events);
            events = AnimationUtility.GetAnimationEvents(clip);
            if (events[num].time != evt.time || events[num].functionName != evt.functionName)
            {
                Debug.LogError("Failed insertion");
            }
            return(num);
        }
        private static void DoEditRegularParameters(AnimationEvent[] events, Type selectedParameter)
        {
            AnimationEvent firstEvent = events[0];

            if (selectedParameter == typeof(AnimationEvent) || selectedParameter == typeof(float))
            {
                bool flag = Array.TrueForAll <AnimationEvent>(events, (AnimationEvent evt) => evt.floatParameter == firstEvent.floatParameter);
                EditorGUI.BeginChangeCheck();
                EditorGUI.showMixedValue = !flag;
                float floatParameter = EditorGUILayout.FloatField("Float", firstEvent.floatParameter, new GUILayoutOption[0]);
                EditorGUI.showMixedValue = false;
                if (EditorGUI.EndChangeCheck())
                {
                    for (int i = 0; i < events.Length; i++)
                    {
                        AnimationEvent animationEvent = events[i];
                        animationEvent.floatParameter = floatParameter;
                    }
                }
            }
            if (selectedParameter == typeof(AnimationEvent) || selectedParameter == typeof(int) || selectedParameter.IsEnum)
            {
                bool flag2 = Array.TrueForAll <AnimationEvent>(events, (AnimationEvent evt) => evt.intParameter == firstEvent.intParameter);
                EditorGUI.BeginChangeCheck();
                EditorGUI.showMixedValue = !flag2;
                int intParameter;
                if (selectedParameter.IsEnum)
                {
                    intParameter = AnimationWindowEventInspector.EnumPopup("Enum", selectedParameter, firstEvent.intParameter);
                }
                else
                {
                    intParameter = EditorGUILayout.IntField("Int", firstEvent.intParameter, new GUILayoutOption[0]);
                }
                EditorGUI.showMixedValue = false;
                if (EditorGUI.EndChangeCheck())
                {
                    for (int j = 0; j < events.Length; j++)
                    {
                        AnimationEvent animationEvent2 = events[j];
                        animationEvent2.intParameter = intParameter;
                    }
                }
            }
            if (selectedParameter == typeof(AnimationEvent) || selectedParameter == typeof(string))
            {
                bool flag3 = Array.TrueForAll <AnimationEvent>(events, (AnimationEvent evt) => evt.stringParameter == firstEvent.stringParameter);
                EditorGUI.BeginChangeCheck();
                EditorGUI.showMixedValue = !flag3;
                string stringParameter = EditorGUILayout.TextField("String", firstEvent.stringParameter, new GUILayoutOption[0]);
                EditorGUI.showMixedValue = false;
                if (EditorGUI.EndChangeCheck())
                {
                    for (int k = 0; k < events.Length; k++)
                    {
                        AnimationEvent animationEvent3 = events[k];
                        animationEvent3.stringParameter = stringParameter;
                    }
                }
            }
            if (selectedParameter == typeof(AnimationEvent) || selectedParameter.IsSubclassOf(typeof(UnityEngine.Object)) || selectedParameter == typeof(UnityEngine.Object))
            {
                bool flag4 = Array.TrueForAll <AnimationEvent>(events, (AnimationEvent evt) => evt.objectReferenceParameter == firstEvent.objectReferenceParameter);
                EditorGUI.BeginChangeCheck();
                Type type = typeof(UnityEngine.Object);
                if (selectedParameter != typeof(AnimationEvent))
                {
                    type = selectedParameter;
                }
                EditorGUI.showMixedValue = !flag4;
                bool allowSceneObjects = false;
                UnityEngine.Object objectReferenceParameter = EditorGUILayout.ObjectField(ObjectNames.NicifyVariableName(type.Name), firstEvent.objectReferenceParameter, type, allowSceneObjects, new GUILayoutOption[0]);
                EditorGUI.showMixedValue = false;
                if (EditorGUI.EndChangeCheck())
                {
                    for (int l = 0; l < events.Length; l++)
                    {
                        AnimationEvent animationEvent4 = events[l];
                        animationEvent4.objectReferenceParameter = objectReferenceParameter;
                    }
                }
            }
        }
Exemple #40
0
 public override void OnAnimationComplete(AnimationEvent evt)
 {
     OnComplete();
 }
 public static void OnEditAnimationEvents(AnimationWindowEvent[] awEvents)
 {
     AnimationWindowEventInspector.AnimationWindowEventData data = AnimationWindowEventInspector.GetData(awEvents);
     if (data.events != null && data.selectedEvents != null && data.selectedEvents.Length != 0)
     {
         AnimationEvent firstEvent = data.selectedEvents[0];
         bool           flag       = Array.TrueForAll <AnimationEvent>(data.selectedEvents, (AnimationEvent evt) => evt.functionName == firstEvent.functionName);
         GUI.changed = false;
         if (data.root != null)
         {
             List <AnimationWindowEventMethod> list = AnimationWindowEventInspector.CollectSupportedMethods(data.root);
             List <string> list2 = new List <string>(list.Count);
             for (int i = 0; i < list.Count; i++)
             {
                 AnimationWindowEventMethod animationWindowEventMethod = list[i];
                 string str = " ( )";
                 if (animationWindowEventMethod.parameterType != null)
                 {
                     if (animationWindowEventMethod.parameterType == typeof(float))
                     {
                         str = " ( float )";
                     }
                     else if (animationWindowEventMethod.parameterType == typeof(int))
                     {
                         str = " ( int )";
                     }
                     else
                     {
                         str = string.Format(" ( {0} )", animationWindowEventMethod.parameterType.Name);
                     }
                 }
                 list2.Add(animationWindowEventMethod.name + str);
             }
             int count = list.Count;
             int num   = list.FindIndex((AnimationWindowEventMethod method) => method.name == firstEvent.functionName);
             if (num == -1)
             {
                 num = list.Count;
                 list.Add(new AnimationWindowEventMethod
                 {
                     name          = firstEvent.functionName,
                     parameterType = null
                 });
                 if (string.IsNullOrEmpty(firstEvent.functionName))
                 {
                     list2.Add("(No Function Selected)");
                 }
                 else
                 {
                     list2.Add(firstEvent.functionName + " (Function Not Supported)");
                 }
             }
             EditorGUIUtility.labelWidth = 130f;
             EditorGUI.showMixedValue    = !flag;
             int num2 = (!flag) ? -1 : num;
             num = EditorGUILayout.Popup("Function: ", num, list2.ToArray(), new GUILayoutOption[0]);
             if (num2 != num && num != -1 && num != count)
             {
                 AnimationEvent[] selectedEvents = data.selectedEvents;
                 for (int j = 0; j < selectedEvents.Length; j++)
                 {
                     AnimationEvent animationEvent = selectedEvents[j];
                     animationEvent.functionName    = list[num].name;
                     animationEvent.stringParameter = string.Empty;
                 }
             }
             EditorGUI.showMixedValue = false;
             Type parameterType = list[num].parameterType;
             if (flag && parameterType != null)
             {
                 EditorGUILayout.Space();
                 if (parameterType == typeof(AnimationEvent))
                 {
                     EditorGUILayout.PrefixLabel("Event Data");
                 }
                 else
                 {
                     EditorGUILayout.PrefixLabel("Parameters");
                 }
                 AnimationWindowEventInspector.DoEditRegularParameters(data.selectedEvents, parameterType);
             }
         }
         else
         {
             EditorGUI.showMixedValue = !flag;
             string text  = (!flag) ? "" : firstEvent.functionName;
             string text2 = EditorGUILayout.TextField(new GUIContent("Function"), text, new GUILayoutOption[0]);
             if (text2 != text)
             {
                 AnimationEvent[] selectedEvents2 = data.selectedEvents;
                 for (int k = 0; k < selectedEvents2.Length; k++)
                 {
                     AnimationEvent animationEvent2 = selectedEvents2[k];
                     animationEvent2.functionName    = text2;
                     animationEvent2.stringParameter = string.Empty;
                 }
             }
             EditorGUI.showMixedValue = false;
             if (flag)
             {
                 AnimationWindowEventInspector.DoEditRegularParameters(data.selectedEvents, typeof(AnimationEvent));
             }
             else
             {
                 using (new EditorGUI.DisabledScope(true))
                 {
                     AnimationEvent animationEvent3 = new AnimationEvent();
                     AnimationWindowEventInspector.DoEditRegularParameters(new AnimationEvent[]
                     {
                         animationEvent3
                     }, typeof(AnimationEvent));
                 }
             }
         }
         if (GUI.changed)
         {
             AnimationWindowEventInspector.SetData(awEvents, data);
         }
     }
 }
 public virtual void Event_ActivateFxAtOpponent(AnimationEvent animEvent)
 {
 }
        private static void DoEditRegularParameters(AnimationEvent[] events, Type selectedParameter)
        {
            AnimationEvent firstEvent = events[0];

            if (selectedParameter == typeof(AnimationEvent) || selectedParameter == typeof(float))
            {
                bool singleParamValue = Array.TrueForAll(events, evt => evt.floatParameter == firstEvent.floatParameter);

                EditorGUI.BeginChangeCheck();
                EditorGUI.showMixedValue = !singleParamValue;
                float newValue = EditorGUILayout.FloatField("Float", firstEvent.floatParameter);
                EditorGUI.showMixedValue = false;

                if (EditorGUI.EndChangeCheck())
                {
                    foreach (var evt in events)
                        evt.floatParameter = newValue;
                }
            }

            if (selectedParameter == typeof(AnimationEvent) || selectedParameter == typeof(int) || selectedParameter.IsEnum)
            {
                bool singleParamValue = Array.TrueForAll(events, evt => evt.intParameter == firstEvent.intParameter);

                EditorGUI.BeginChangeCheck();
                EditorGUI.showMixedValue = !singleParamValue;
                int newValue = 0;
                if (selectedParameter.IsEnum)
                    newValue = EnumPopup("Enum", selectedParameter, firstEvent.intParameter);
                else
                    newValue = EditorGUILayout.IntField("Int", firstEvent.intParameter);
                EditorGUI.showMixedValue = false;

                if (EditorGUI.EndChangeCheck())
                {
                    foreach (var evt in events)
                        evt.intParameter = newValue;
                }
            }

            if (selectedParameter == typeof(AnimationEvent) || selectedParameter == typeof(string))
            {
                bool singleParamValue = Array.TrueForAll(events, evt => evt.stringParameter == firstEvent.stringParameter);

                EditorGUI.BeginChangeCheck();
                EditorGUI.showMixedValue = !singleParamValue;
                string newValue = EditorGUILayout.TextField("String", firstEvent.stringParameter);
                EditorGUI.showMixedValue = false;

                if (EditorGUI.EndChangeCheck())
                {
                    foreach (var evt in events)
                        evt.stringParameter = newValue;
                }
            }

            if (selectedParameter == typeof(AnimationEvent) || selectedParameter.IsSubclassOf(typeof(UnityEngine.Object)) || selectedParameter == typeof(UnityEngine.Object))
            {
                bool singleParamValue = Array.TrueForAll(events, evt => evt.objectReferenceParameter == firstEvent.objectReferenceParameter);

                EditorGUI.BeginChangeCheck();
                Type type = typeof(UnityEngine.Object);
                if (selectedParameter != typeof(AnimationEvent))
                    type = selectedParameter;

                EditorGUI.showMixedValue = !singleParamValue;
                bool allowSceneObjects = false;
                Object newValue = EditorGUILayout.ObjectField(ObjectNames.NicifyVariableName(type.Name), firstEvent.objectReferenceParameter, type, allowSceneObjects);
                EditorGUI.showMixedValue = false;

                if (EditorGUI.EndChangeCheck())
                {
                    foreach (var evt in events)
                        evt.objectReferenceParameter = newValue;
                }
            }
        }
Exemple #44
0
    public void KickPlayer()
    {
        AnimationEvent ae = new AnimationEvent();

        ae.messageOptions = SendMessageOptions.DontRequireReceiver;
    }
Exemple #45
0
 private void OnAllActionEnd(AnimationEvent e)
 {
     this.animatorDoneNum++;
 }
Exemple #46
0
 // activation of events. -- all unit copies use same animation!
 void InitAnimationWithCallback(Animator character, string animationName, AnimationEvent evt)
 {
 }
 public virtual void Event_ActivateFx(AnimationEvent animEvent)
 {
 }
Exemple #48
0
	static void ParseEventTimeline (EventTimeline timeline, AnimationClip clip, SendMessageOptions eventOptions) {

		float[] frames = timeline.Frames;
		var events = timeline.Events;

		List<AnimationEvent> animEvents = new List<AnimationEvent>();
		for (int i = 0; i < frames.Length; i++) {
			var ev = events[i];

			AnimationEvent ae = new AnimationEvent();
			//TODO:  Deal with Mecanim's zero-time missed event
			ae.time = frames[i];
			ae.functionName = ev.Data.Name;
			ae.messageOptions = eventOptions;

			if (ev.String != "" && ev.String != null) {
				ae.stringParameter = ev.String;
			} else {
				if (ev.Int == 0 && ev.Float == 0) {
					//do nothing, raw function
				} else {
					if (ev.Int != 0)
						ae.floatParameter = (float)ev.Int;
					else
						ae.floatParameter = ev.Float;
				}

			}

			animEvents.Add(ae);
		}

		AnimationUtility.SetAnimationEvents(clip, animEvents.ToArray());
	}
Exemple #49
0
 private void OnAllActionStart(AnimationEvent e)
 {
 }
 public virtual void Event_MoveBack(AnimationEvent animEvent)
 {
 }
Exemple #51
0
 // 足音(無効).
 public void PlayStepSound(AnimationEvent ev)
 {
 }
Exemple #52
0
        public override void Process(ImportContext ctx, Layer layer)
        {
            var eventFrames = new HashSet <int>();
            var file        = ctx.file;

            for (int i = 0; i < file.frames.Count; ++i)
            {
                bool isEvent = file.frames[i].cels.ContainsKey(layer.index);
                if (isEvent)
                {
                    eventFrames.Add(i);
                }
            }

            LayerParamType paramType = layer.GetParamType(1);

            foreach (var frametag in file.frameTags)
            {
                var clip   = ctx.generatedClips[frametag];
                var events = new List <AnimationEvent>(clip.events);

                var time = 0.0f;
                for (int f = frametag.from; f <= frametag.to; ++f)
                {
                    if (eventFrames.Contains(f))
                    {
                        var evt = new AnimationEvent {
                            time           = time,
                            functionName   = layer.GetParamString(0),
                            messageOptions = SendMessageOptions.DontRequireReceiver
                        };

                        // Debug.Log(paramType + ", " + layer.metaInfo.ParamCount);

                        if (paramType == LayerParamType.String)
                        {
                            evt.stringParameter = layer.GetParamString(1);
                        }
                        else if (paramType == LayerParamType.Number)
                        {
                            var fval = layer.GetParamFloat(1);
                            if (fval == Math.Floor(fval))
                            {
                                evt.intParameter = (int)fval;
                            }
                            else
                            {
                                evt.floatParameter = fval;
                            }
                        }

                        events.Add(evt);
                    }

                    time += file.frames[f].duration * 1e-3f;
                }

                events.Sort((lhs, rhs) => lhs.time.CompareTo(rhs.time));
                AnimationUtility.SetAnimationEvents(clip, events.ToArray());
                EditorUtility.SetDirty(clip);
            }
        }
Exemple #53
0
        public void EventLineGUI(Rect rect, AnimationSelection selection, AnimationWindowState state, CurveEditor curveEditor)
        {
            AnimationClip activeAnimationClip = state.m_ActiveAnimationClip;
            GameObject    rootGameObject      = state.m_RootGameObject;

            GUI.BeginGroup(rect);
            Color color = GUI.color;
            Rect  rect2 = new Rect(0f, 0f, rect.width, rect.height);
            float time  = (float)Mathf.RoundToInt(state.PixelToTime(Event.current.mousePosition.x, rect) * state.frameRate) / state.frameRate;

            if (activeAnimationClip != null)
            {
                AnimationEvent[] animationEvents = AnimationUtility.GetAnimationEvents(activeAnimationClip);
                Texture          image           = EditorGUIUtility.IconContent("Animation.EventMarker").image;
                Rect[]           array           = new Rect[animationEvents.Length];
                Rect[]           array2          = new Rect[animationEvents.Length];
                int num  = 1;
                int num2 = 0;
                for (int i = 0; i < animationEvents.Length; i++)
                {
                    AnimationEvent animationEvent = animationEvents[i];
                    if (num2 == 0)
                    {
                        num = 1;
                        while (i + num < animationEvents.Length && animationEvents[i + num].time == animationEvent.time)
                        {
                            num++;
                        }
                        num2 = num;
                    }
                    num2--;
                    float num3 = Mathf.Floor(state.FrameToPixel(animationEvent.time * activeAnimationClip.frameRate, rect));
                    int   num4 = 0;
                    if (num > 1)
                    {
                        float num5 = (float)Mathf.Min((num - 1) * (image.width - 1), (int)(state.FrameDeltaToPixel(rect) - (float)(image.width * 2)));
                        num4 = Mathf.FloorToInt(Mathf.Max(0f, num5 - (float)((image.width - 1) * num2)));
                    }
                    Rect rect3 = new Rect(num3 + (float)num4 - (float)(image.width / 2), (rect.height - 10f) * (float)(num2 - num + 1) / (float)Mathf.Max(1, num - 1), (float)image.width, (float)image.height);
                    array[i]  = rect3;
                    array2[i] = rect3;
                }
                if (this.m_DirtyTooltip)
                {
                    if (this.m_HoverEvent >= 0 && this.m_HoverEvent < array.Length)
                    {
                        this.m_InstantTooltipText  = AnimationEventPopup.FormatEvent(rootGameObject, animationEvents[this.m_HoverEvent]);
                        this.m_InstantTooltipPoint = new Vector2(array[this.m_HoverEvent].xMin + (float)((int)(array[this.m_HoverEvent].width / 2f)) + rect.x - 30f, rect.yMax);
                    }
                    this.m_DirtyTooltip = false;
                }
                if (this.m_EventsSelected == null || this.m_EventsSelected.Length != animationEvents.Length)
                {
                    this.m_EventsSelected = new bool[animationEvents.Length];
                    AnimationEventPopup.ClosePopup();
                }
                Vector2        zero = Vector2.zero;
                int            num6;
                float          num7;
                float          num8;
                HighLevelEvent highLevelEvent = EditorGUIExt.MultiSelection(rect, array2, new GUIContent(image), array, ref this.m_EventsSelected, null, out num6, out zero, out num7, out num8, GUIStyleX.none);
                if (highLevelEvent != HighLevelEvent.None)
                {
                    switch (highLevelEvent)
                    {
                    case HighLevelEvent.DoubleClick:
                        if (num6 != -1)
                        {
                            AnimationEventPopup.Edit(rootGameObject, selection.clip, num6, this.m_Owner);
                        }
                        else
                        {
                            this.EventLineContextMenuAdd(new AnimationEventTimeLine.EventLineContextMenuObject(rootGameObject, activeAnimationClip, time, -1));
                        }
                        break;

                    case HighLevelEvent.ContextClick:
                    {
                        GenericMenu genericMenu = new GenericMenu();
                        AnimationEventTimeLine.EventLineContextMenuObject userData = new AnimationEventTimeLine.EventLineContextMenuObject(rootGameObject, activeAnimationClip, animationEvents[num6].time, num6);
                        genericMenu.AddItem(new GUIContent("Edit Animation Event"), false, new GenericMenu.MenuFunction2(this.EventLineContextMenuEdit), userData);
                        genericMenu.AddItem(new GUIContent("Add Animation Event"), false, new GenericMenu.MenuFunction2(this.EventLineContextMenuAdd), userData);
                        genericMenu.AddItem(new GUIContent("Delete Animation Event"), false, new GenericMenu.MenuFunction2(this.EventLineContextMenuDelete), userData);
                        genericMenu.ShowAsContext();
                        this.m_InstantTooltipText = null;
                        this.m_DirtyTooltip       = true;
                        state.Repaint();
                        break;
                    }

                    case HighLevelEvent.BeginDrag:
                        this.m_EventsAtMouseDown = animationEvents;
                        this.m_EventTimes        = new float[animationEvents.Length];
                        for (int j = 0; j < animationEvents.Length; j++)
                        {
                            this.m_EventTimes[j] = animationEvents[j].time;
                        }
                        break;

                    case HighLevelEvent.Drag:
                    {
                        for (int k = animationEvents.Length - 1; k >= 0; k--)
                        {
                            if (this.m_EventsSelected[k])
                            {
                                AnimationEvent animationEvent2 = this.m_EventsAtMouseDown[k];
                                animationEvent2.time        = this.m_EventTimes[k] + zero.x * state.PixelDeltaToTime(rect);
                                animationEvent2.time        = Mathf.Max(0f, animationEvent2.time);
                                animationEvent2.time        = (float)Mathf.RoundToInt(animationEvent2.time * activeAnimationClip.frameRate) / activeAnimationClip.frameRate;
                                this.m_EventsAtMouseDown[k] = animationEvent2;
                            }
                        }
                        int[] array3 = new int[this.m_EventsSelected.Length];
                        for (int l = 0; l < array3.Length; l++)
                        {
                            array3[l] = l;
                        }
                        Array.Sort(this.m_EventsAtMouseDown, array3, new AnimationEventTimeLine.EventComparer());
                        bool[]  array4 = (bool[])this.m_EventsSelected.Clone();
                        float[] array5 = (float[])this.m_EventTimes.Clone();
                        for (int m = 0; m < array3.Length; m++)
                        {
                            this.m_EventsSelected[m] = array4[array3[m]];
                            this.m_EventTimes[m]     = array5[array3[m]];
                        }
                        Undo.RegisterCompleteObjectUndo(activeAnimationClip, "Move Event");
                        AnimationUtility.SetAnimationEvents(activeAnimationClip, this.m_EventsAtMouseDown);
                        this.m_DirtyTooltip = true;
                        break;
                    }

                    case HighLevelEvent.Delete:
                        this.DeleteEvents(activeAnimationClip, this.m_EventsSelected);
                        break;

                    case HighLevelEvent.SelectionChanged:
                        curveEditor.SelectNone();
                        if (num6 != -1)
                        {
                            AnimationEventPopup.UpdateSelection(rootGameObject, selection.clip, num6, this.m_Owner);
                        }
                        break;
                    }
                }
                this.CheckRectsOnMouseMove(rect, animationEvents, array);
            }
            if (Event.current.type == EventType.ContextClick && rect2.Contains(Event.current.mousePosition) && selection.EnsureClipPresence())
            {
                Event.current.Use();
                GenericMenu genericMenu2 = new GenericMenu();
                genericMenu2.AddItem(new GUIContent("Add Animation Event"), false, new GenericMenu.MenuFunction2(this.EventLineContextMenuAdd), new AnimationEventTimeLine.EventLineContextMenuObject(rootGameObject, activeAnimationClip, time, -1));
                genericMenu2.ShowAsContext();
            }
            GUI.color = color;
            GUI.EndGroup();
        }
    public void SetAnimationEffects()
    {
        var effectsByAnimationClip = effects.GroupBy(c => c.targetAnimationClip).Select(grp => grp.ToList()).ToList();

        foreach (var e in effectsByAnimationClip)
        {
            List <AnimationEvent> newEvents = new List <AnimationEvent>();
            foreach (AnimationEffect effect in e)
            {
                var curveBindings      = AnimationUtility.GetObjectReferenceCurveBindings(effect.targetAnimationClip);
                var spriteCurveBinding = curveBindings.First(c => c.type == typeof(SpriteRenderer));

                if (spriteCurveBinding != null)
                {
                    var keyframes = AnimationUtility.GetObjectReferenceCurve(effect.targetAnimationClip, spriteCurveBinding);
                    if (keyframes != null && keyframes.Length > 1)
                    {
                        int keyframeToPlayAt = Mathf.Clamp(effect.frameToPlayIn - 1, 0, keyframes.Length - 1);

                        float keyframeTime = keyframes[keyframeToPlayAt].time;

                        if (effect.frameToPlayIn > keyframes.Length)
                        {
                            keyframeTime = effect.targetAnimationClip.length;
                        }

                        var evnt = new AnimationEvent();
                        evnt.time = keyframeTime;

                        switch (effect.selectedParameterType)
                        {
                        case AnimationEffect.parameterType.OBJECT:
                            if (effect.objectValue != null)
                            {
                                evnt.objectReferenceParameter = effect.objectValue;
                            }
                            break;

                        case AnimationEffect.parameterType.BOOLEAN:
                            evnt.intParameter = effect.booleanValue;
                            break;

                        case AnimationEffect.parameterType.FLOAT:
                            evnt.floatParameter = effect.floatValue;
                            break;
                        }

                        if (!String.IsNullOrEmpty(effect.methodName))
                        {
                            evnt.functionName = effect.methodName;
                        }

                        newEvents.Add(evnt);
                    }
                }
            }

            newEvents = newEvents.OrderBy(c => c.time).ToList();

            AnimationUtility.SetAnimationEvents(e.First().targetAnimationClip, newEvents.ToArray());
        }
    }
Exemple #55
0
 //设置动作相应
 public void setAnimationEvent( Animation am, AnimationEvent e )
 {
 }
 public virtual void EventMoveToOpponent(AnimationEvent animEvent)
 {
     Event_MoveToOpponent(animEvent);
 }
Exemple #57
0
    /// <summary>
    /// Collision ends
    /// </summary>
    /// <param name="col"></param>
    //void OnCollisionExit(Collision col)
    //{
    //    if (col.gameObject.layer == LayerMask.NameToLayer("Geometry"))
    //    {
    //        if (transform.parent == col.transform)
    //        {
    //            //transform.parent = null;
    //        }
    //    }
    //}

    // ####################################################################################################################################### Animation Events

    /// <summary>
    /// Draw weapon
    /// Triggered when hand reaches sword position in draw animation
    /// </summary>
    /// <param name="evt"></param>
    public void DrawWeapon(AnimationEvent evt)
    {
        if (evt.animatorClipInfo.weight > 0.5f) //&& evt.intParameter == a.GetDominantLayer())
        {
            if (!is_weapon_equiped)
            {
                // ######################################################################################################## TEMP
                sword.SetActive(true);
                sword_holstered.SetActive(false);
                shield.SetActive(true);
                shield_holstered.SetActive(false);
                // ######################################################################################################## TEMP
                AudioSource.PlayClipAtPoint(Sounds.SwordDraw, transform.position, Settings.SoundVolume);
                a.SetBool(AnimatorConditions.WeaponIsOut, true);                
                a.SetLayerWeight(0, 0f);
                a.SetLayerWeight(1, 1f);
            }
            else
            {
                // ######################################################################################################## TEMP
                sword.SetActive(false);
                sword_holstered.SetActive(true);
                shield.SetActive(false);
                shield_holstered.SetActive(true);
                // ######################################################################################################## TEMP
                AudioSource.PlayClipAtPoint(Sounds.SwordSheath, transform.position, Settings.SoundVolume);
                a.SetBool(AnimatorConditions.WeaponIsOut, false);
                a.SetLayerWeight(0, 1f);
                a.SetLayerWeight(1, 0f);
            }
            is_weapon_equiped = !is_weapon_equiped;
        }
    }
        public void EventLineGUI(Rect rect, AnimationWindowState state)
        {
            if (!(state.selectedItem == null))
            {
                AnimationClip animationClip  = state.selectedItem.animationClip;
                GameObject    rootGameObject = state.selectedItem.rootGameObject;
                GUI.BeginGroup(rect);
                Color color = GUI.color;
                Rect  rect2 = new Rect(0f, 0f, rect.width, rect.height);
                float time  = Mathf.Max((float)Mathf.RoundToInt(state.PixelToTime(Event.current.mousePosition.x, rect) * state.frameRate) / state.frameRate, 0f);
                if (animationClip != null)
                {
                    AnimationEvent[] animationEvents = AnimationUtility.GetAnimationEvents(animationClip);
                    Texture          image           = EditorGUIUtility.IconContent("Animation.EventMarker").image;
                    Rect[]           array           = new Rect[animationEvents.Length];
                    Rect[]           array2          = new Rect[animationEvents.Length];
                    int num  = 1;
                    int num2 = 0;
                    for (int i = 0; i < animationEvents.Length; i++)
                    {
                        AnimationEvent animationEvent = animationEvents[i];
                        if (num2 == 0)
                        {
                            num = 1;
                            while (i + num < animationEvents.Length && animationEvents[i + num].time == animationEvent.time)
                            {
                                num++;
                            }
                            num2 = num;
                        }
                        num2--;
                        float num3 = Mathf.Floor(state.FrameToPixel(animationEvent.time * animationClip.frameRate, rect));
                        int   num4 = 0;
                        if (num > 1)
                        {
                            float num5 = (float)Mathf.Min((num - 1) * (image.width - 1), (int)(state.FrameDeltaToPixel(rect) - (float)(image.width * 2)));
                            num4 = Mathf.FloorToInt(Mathf.Max(0f, num5 - (float)((image.width - 1) * num2)));
                        }
                        Rect rect3 = new Rect(num3 + (float)num4 - (float)(image.width / 2), (rect.height - 10f) * (float)(num2 - num + 1) / (float)Mathf.Max(1, num - 1), (float)image.width, (float)image.height);
                        array[i]  = rect3;
                        array2[i] = rect3;
                    }
                    if (this.m_DirtyTooltip)
                    {
                        if (this.m_HoverEvent >= 0 && this.m_HoverEvent < array.Length)
                        {
                            this.m_InstantTooltipText  = AnimationWindowEventInspector.FormatEvent(rootGameObject, animationEvents[this.m_HoverEvent]);
                            this.m_InstantTooltipPoint = new Vector2(array[this.m_HoverEvent].xMin + (float)((int)(array[this.m_HoverEvent].width / 2f)) + rect.x - 30f, rect.yMax);
                        }
                        this.m_DirtyTooltip = false;
                    }
                    bool[] array3 = new bool[animationEvents.Length];
                    UnityEngine.Object[] objects = Selection.objects;
                    UnityEngine.Object[] array4  = objects;
                    for (int j = 0; j < array4.Length; j++)
                    {
                        UnityEngine.Object   @object = array4[j];
                        AnimationWindowEvent animationWindowEvent = @object as AnimationWindowEvent;
                        if (animationWindowEvent != null)
                        {
                            if (animationWindowEvent.eventIndex >= 0 && animationWindowEvent.eventIndex < array3.Length)
                            {
                                array3[animationWindowEvent.eventIndex] = true;
                            }
                        }
                    }
                    Vector2        zero = Vector2.zero;
                    int            num6;
                    float          num7;
                    float          num8;
                    HighLevelEvent highLevelEvent = EditorGUIExt.MultiSelection(rect, array2, new GUIContent(image), array, ref array3, null, out num6, out zero, out num7, out num8, GUIStyle.none);
                    if (highLevelEvent != HighLevelEvent.None)
                    {
                        switch (highLevelEvent)
                        {
                        case HighLevelEvent.DoubleClick:
                            if (num6 != -1)
                            {
                                this.EditEvents(rootGameObject, animationClip, array3);
                            }
                            else
                            {
                                this.EventLineContextMenuAdd(new AnimationEventTimeLine.EventLineContextMenuObject(rootGameObject, animationClip, time, -1, array3));
                            }
                            break;

                        case HighLevelEvent.ContextClick:
                        {
                            GenericMenu genericMenu = new GenericMenu();
                            AnimationEventTimeLine.EventLineContextMenuObject userData = new AnimationEventTimeLine.EventLineContextMenuObject(rootGameObject, animationClip, animationEvents[num6].time, num6, array3);
                            int num9 = array3.Count((bool selected) => selected);
                            genericMenu.AddItem(new GUIContent("Add Animation Event"), false, new GenericMenu.MenuFunction2(this.EventLineContextMenuAdd), userData);
                            genericMenu.AddItem(new GUIContent((num9 <= 1) ? "Delete Animation Event" : "Delete Animation Events"), false, new GenericMenu.MenuFunction2(this.EventLineContextMenuDelete), userData);
                            genericMenu.ShowAsContext();
                            this.m_InstantTooltipText = null;
                            this.m_DirtyTooltip       = true;
                            state.Repaint();
                            break;
                        }

                        case HighLevelEvent.BeginDrag:
                            this.m_EventsAtMouseDown = animationEvents;
                            this.m_EventTimes        = new float[animationEvents.Length];
                            for (int k = 0; k < animationEvents.Length; k++)
                            {
                                this.m_EventTimes[k] = animationEvents[k].time;
                            }
                            break;

                        case HighLevelEvent.Drag:
                        {
                            for (int l = animationEvents.Length - 1; l >= 0; l--)
                            {
                                if (array3[l])
                                {
                                    AnimationEvent animationEvent2 = this.m_EventsAtMouseDown[l];
                                    animationEvent2.time = this.m_EventTimes[l] + zero.x * state.PixelDeltaToTime(rect);
                                    animationEvent2.time = Mathf.Max(0f, animationEvent2.time);
                                    animationEvent2.time = (float)Mathf.RoundToInt(animationEvent2.time * animationClip.frameRate) / animationClip.frameRate;
                                }
                            }
                            int[] array5 = new int[array3.Length];
                            for (int m = 0; m < array5.Length; m++)
                            {
                                array5[m] = m;
                            }
                            Array.Sort(this.m_EventsAtMouseDown, array5, new AnimationEventTimeLine.EventComparer());
                            bool[]  array6 = (bool[])array3.Clone();
                            float[] array7 = (float[])this.m_EventTimes.Clone();
                            for (int n = 0; n < array5.Length; n++)
                            {
                                array3[n]            = array6[array5[n]];
                                this.m_EventTimes[n] = array7[array5[n]];
                            }
                            this.EditEvents(rootGameObject, animationClip, array3);
                            Undo.RegisterCompleteObjectUndo(animationClip, "Move Event");
                            AnimationUtility.SetAnimationEvents(animationClip, this.m_EventsAtMouseDown);
                            this.m_DirtyTooltip = true;
                            break;
                        }

                        case HighLevelEvent.Delete:
                            this.DeleteEvents(animationClip, array3);
                            break;

                        case HighLevelEvent.SelectionChanged:
                            state.ClearKeySelections();
                            this.EditEvents(rootGameObject, animationClip, array3);
                            break;
                        }
                    }
                    this.CheckRectsOnMouseMove(rect, animationEvents, array);
                    if (Event.current.type == EventType.ContextClick && rect2.Contains(Event.current.mousePosition))
                    {
                        Event.current.Use();
                        GenericMenu genericMenu2 = new GenericMenu();
                        AnimationEventTimeLine.EventLineContextMenuObject userData2 = new AnimationEventTimeLine.EventLineContextMenuObject(rootGameObject, animationClip, time, -1, array3);
                        int num10 = array3.Count((bool selected) => selected);
                        genericMenu2.AddItem(new GUIContent("Add Animation Event"), false, new GenericMenu.MenuFunction2(this.EventLineContextMenuAdd), userData2);
                        if (num10 > 0)
                        {
                            genericMenu2.AddItem(new GUIContent((num10 <= 1) ? "Delete Animation Event" : "Delete Animation Events"), false, new GenericMenu.MenuFunction2(this.EventLineContextMenuDelete), userData2);
                        }
                        genericMenu2.ShowAsContext();
                    }
                }
                GUI.color = color;
                GUI.EndGroup();
            }
        }
Exemple #59
0
    /// <summary>
    /// Footstep sounds
    /// Triggered on every foot step
    /// </summary>
    /// <param name="evt"></param>
	public void Foot(AnimationEvent evt)
    {
        if (evt.animatorClipInfo.weight > 0.5f && evt.intParameter == a.GetDominantLayer())
        {
            AudioSource.PlayClipAtPoint(Sounds.FootStep, transform.position, Settings.SoundVolume);
        }
    }
Exemple #60
0
        public bool HandleEventManipulation(Rect rect, ref AnimationEvent[] events, AnimationClipInfoProperties clipInfo)
        {
            Texture image  = EditorGUIUtility.IconContent("Animation.EventMarker").image;
            bool    result = false;

            Rect[] array  = new Rect[events.Length];
            Rect[] array2 = new Rect[events.Length];
            int    num    = 1;
            int    num2   = 0;

            for (int i = 0; i < events.Length; i++)
            {
                AnimationEvent animationEvent = events[i];
                if (num2 == 0)
                {
                    num = 1;
                    while (i + num < events.Length && events[i + num].time == animationEvent.time)
                    {
                        num++;
                    }
                    num2 = num;
                }
                num2--;
                float num3 = Mathf.Floor(this.m_Timeline.TimeToPixel(animationEvent.time, rect));
                int   num4 = 0;
                if (num > 1)
                {
                    float num5 = (float)Mathf.Min((num - 1) * (image.width - 1), (int)(1f / this.m_Timeline.PixelDeltaToTime(rect) - (float)(image.width * 2)));
                    num4 = Mathf.FloorToInt(Mathf.Max(0f, num5 - (float)((image.width - 1) * num2)));
                }
                Rect rect2 = new Rect(num3 + (float)num4 - (float)(image.width / 2), (rect.height - 10f) * (float)(num2 - num + 1) / (float)Mathf.Max(1, num - 1), (float)image.width, (float)image.height);
                array[i]  = rect2;
                array2[i] = rect2;
            }
            this.m_EventRects = new Rect[array.Length];
            for (int j = 0; j < array.Length; j++)
            {
                this.m_EventRects[j] = new Rect(array[j].x + rect.x, array[j].y + rect.y, array[j].width, array[j].height);
            }
            if (this.m_EventsSelected == null || this.m_EventsSelected.Length != events.Length || this.m_EventsSelected.Length == 0)
            {
                this.m_EventsSelected = new bool[events.Length];
                this.m_Events         = null;
            }
            Vector2        zero = Vector2.zero;
            int            num6;
            float          num7;
            float          num8;
            HighLevelEvent highLevelEvent = EditorGUIExt.MultiSelection(rect, array2, new GUIContent(image), array, ref this.m_EventsSelected, null, out num6, out zero, out num7, out num8, GUIStyle.none);

            if (highLevelEvent != HighLevelEvent.None)
            {
                switch (highLevelEvent)
                {
                case HighLevelEvent.ContextClick:
                {
                    int         num9        = this.m_EventsSelected.Count((bool selected) => selected);
                    GenericMenu genericMenu = new GenericMenu();
                    genericMenu.AddItem(EditorGUIUtility.TrTextContent("Add Animation Event", null, null), false, new GenericMenu.MenuFunction2(this.EventLineContextMenuAdd), new EventManipulationHandler.EventModificationContextMenuObject(clipInfo, events[num6].time, num6, this.m_EventsSelected));
                    genericMenu.AddItem((num9 <= 1) ? this.m_DeleteAnimationEventText : this.m_DeleteAnimationEventsText, false, new GenericMenu.MenuFunction2(this.EventLineContextMenuDelete), new EventManipulationHandler.EventModificationContextMenuObject(clipInfo, events[num6].time, num6, this.m_EventsSelected));
                    genericMenu.ShowAsContext();
                    this.m_InstantTooltipText = null;
                    break;
                }

                case HighLevelEvent.BeginDrag:
                    EventManipulationHandler.m_EventsAtMouseDown = events;
                    EventManipulationHandler.m_EventTimes        = new float[events.Length];
                    for (int k = 0; k < events.Length; k++)
                    {
                        EventManipulationHandler.m_EventTimes[k] = events[k].time;
                    }
                    break;

                case HighLevelEvent.Drag:
                {
                    for (int l = events.Length - 1; l >= 0; l--)
                    {
                        if (this.m_EventsSelected[l])
                        {
                            AnimationEvent animationEvent2 = EventManipulationHandler.m_EventsAtMouseDown[l];
                            animationEvent2.time = Mathf.Clamp01(EventManipulationHandler.m_EventTimes[l] + zero.x / rect.width);
                        }
                    }
                    int[] array3 = new int[this.m_EventsSelected.Length];
                    for (int m = 0; m < array3.Length; m++)
                    {
                        array3[m] = m;
                    }
                    Array.Sort(EventManipulationHandler.m_EventsAtMouseDown, array3, new AnimationEventTimeLine.EventComparer());
                    bool[]  array4 = (bool[])this.m_EventsSelected.Clone();
                    float[] array5 = (float[])EventManipulationHandler.m_EventTimes.Clone();
                    for (int n = 0; n < array3.Length; n++)
                    {
                        this.m_EventsSelected[n] = array4[array3[n]];
                        EventManipulationHandler.m_EventTimes[n] = array5[array3[n]];
                    }
                    events = EventManipulationHandler.m_EventsAtMouseDown;
                    result = true;
                    break;
                }

                case HighLevelEvent.Delete:
                    result = this.DeleteEvents(ref events, this.m_EventsSelected);
                    break;

                case HighLevelEvent.SelectionChanged:
                    this.EditEvents(clipInfo, this.m_EventsSelected);
                    break;
                }
            }
            if (Event.current.type == EventType.ContextClick && rect.Contains(Event.current.mousePosition))
            {
                Event.current.Use();
                int         num10        = this.m_EventsSelected.Count((bool selected) => selected);
                float       time         = Mathf.Max(this.m_Timeline.PixelToTime(Event.current.mousePosition.x, rect), 0f);
                GenericMenu genericMenu2 = new GenericMenu();
                genericMenu2.AddItem(EditorGUIUtility.TrTextContent("Add Animation Event", null, null), false, new GenericMenu.MenuFunction2(this.EventLineContextMenuAdd), new EventManipulationHandler.EventModificationContextMenuObject(clipInfo, time, -1, this.m_EventsSelected));
                if (num10 > 0)
                {
                    genericMenu2.AddItem((num10 <= 1) ? this.m_DeleteAnimationEventText : this.m_DeleteAnimationEventsText, false, new GenericMenu.MenuFunction2(this.EventLineContextMenuDelete), new EventManipulationHandler.EventModificationContextMenuObject(clipInfo, time, -1, this.m_EventsSelected));
                }
                genericMenu2.ShowAsContext();
                this.m_InstantTooltipText = null;
            }
            this.CheckRectsOnMouseMove(rect, events, array);
            return(result);
        }