Example #1
0
        public Machinegun(AbstractScene scene, Hero hero) : base(scene, hero)
        {
            Animations = new AnimationStateMachine();
            RemoveComponent <AnimationStateMachine>();
            AddComponent(Animations);
            AllAmmo = 0;
            //LeftFacingOffset = new Vector2(50, 0);
            //RightFacingOffset = new Vector2(-50, 0);

            if (hero.CurrentFaceDirection == Direction.EAST)
            {
                Transform.Position = RightFacingOffset;
            }
            else
            {
                Transform.Position = LeftFacingOffset;
            }

            /*SpriteSheetAnimation machineGunLeft = new SpriteSheetAnimation(this, Assets.GetTexture("Machinegun"), 1);
             * Animations.RegisterAnimation("MachineGunLeft", machineGunLeft, () => CurrentFaceDirection == Direction.WEST);
             *
             * SpriteSheetAnimation machineGunRight = machineGunLeft.CopyFlipped();
             * machineGunLeft.FlipVertical();
             * Animations.RegisterAnimation("MachineGunRight", machineGunRight, () => CurrentFaceDirection == Direction.EAST);*/

            SpriteSheetAnimation animLeft  = new SpriteSheetAnimation(this, Assets.GetTexture("Machinegun"), 32, 32, 1);
            SpriteSheetAnimation animRight = animLeft.CopyFlipped();

            animLeft = animLeft.CopyFlipped();
            animLeft.FlipVertical();
            Animations.RegisterAnimation("MachineGunLeft", animLeft, () => CurrentFaceDirection == Direction.WEST);
            Animations.RegisterAnimation("MachineGunRight", animRight, () => CurrentFaceDirection == Direction.EAST);
        }
Example #2
0
    public override void _Ready()
    {
        base._Ready();
        // get references to scene components to be used
        _attackTimer = GetNode <Timer>("AttackTimer");

        // load packed scenes
        _weaponPS   = (PackedScene)ResourceLoader.Load("res://MeleeCarry1/MeleeCarry1_weapon.tscn");
        _markWavePS = (PackedScene)ResourceLoader.Load("res://MeleeCarry1/MarkWave.tscn");
        _totemPS    = (PackedScene)ResourceLoader.Load("res://MeleeCarry1/TeleportationTotem.tscn");

        // get spawn positions
        _leftSwordSpawn  = GetNode <Position3D>("Armature/Skeleton/headAttachment/LeftSwordSpawnPoint");
        _rightSwordSpawn = GetNode <Position3D>("Armature/Skeleton/headAttachment/RightSwordSpawnPoint");
        _waveSpawn       = GetNode <Position3D>("Armature/Skeleton/headAttachment/MarkWaveSpawnPoint");

        // connect interaction area to body for sword pickup
        GetNode <Area>("InteractionArea").Connect("area_entered", this, "InteractionCallback");

        // setup references to state machine
        _stateMachineController = (AnimationNodeStateMachinePlayback)_animationTree.Get("parameters/stateMachine/playback");
        AnimationNodeBlendTree    treeRoot          = (AnimationNodeBlendTree)_animationTree.TreeRoot;
        AnimationNodeStateMachine stateMachineChild = (AnimationNodeStateMachine)treeRoot.GetNode("stateMachine");

        _stateMachine = new AnimationStateMachine(stateMachineChild, _stateMachineController);
    }
Example #3
0
    public override void InitAnimation(AnimationStateMachine stateMachine)
    {
        var inputHolder = stateMachine.GetComponent <InputHolder>();
        var movement    = stateMachine.GetComponent <RigidbodyMovementRotationVelocity>();

        var idleState   = stateMachine.AddNewStateAsCurrent("Idle");
        var tongueState = stateMachine.AddNewState("Tongue");

        idleState.AddTransition(tongueState, new AnimationBlendData(0.25f));

        idleState.AddUpdate((s) =>
        {
            stateMachine.animator.SetBool("atWalk", inputHolder.atMove);
        });

        Timer tGlide  = new Timer(2.75f);
        Timer cdGlide = new Timer(0.5f);

        tongueState
        .AddCanEnter(() => inputHolder.keys[0])
        .AddCanEnter(() => cdGlide.IsReady())
        .AddOnEnd(() => cdGlide.Restart())
        .AddOnBegin(tGlide.Restart)
        .AddUpdate((t) =>
        {
            inputHolder.rotationInput = inputHolder.directionInput;
            if (!inputHolder.keys[0])
            {
                AutoTransition(stateMachine, idleState, new AnimationBlendData(0.35f, 0.0f), 0.85f);
            }
        })
        .AddOnEnd(() => inputHolder.rotationInput = Vector2.zero);
    }
Example #4
0
        AnimationStateMachine CreateAnimationStateMachine(int tileSize)
        {
            AnimationStateMachine asm = new AnimationStateMachine("idle down");

            Predicate <Character> up = chara => chara.Path != null && chara.Tile != null && chara.CurrentWaypoint < chara.Path.Length &&
                                       (chara.Tile.Position - chara.Path[chara.CurrentWaypoint].Position + new Vector2(0, -tileSize)).LengthSquared() < 1e-6;

            Predicate <Character> left = chara => chara.Path != null && chara.Tile != null && chara.CurrentWaypoint < chara.Path.Length &&
                                         (chara.Tile.Position - chara.Path[chara.CurrentWaypoint].Position + new Vector2(-tileSize, 0)).LengthSquared() < 1e-6;

            Predicate <Character> right = chara => chara.Path != null && chara.Tile != null && chara.CurrentWaypoint < chara.Path.Length &&
                                          (chara.Tile.Position - chara.Path[chara.CurrentWaypoint].Position + new Vector2(tileSize, 0)).LengthSquared() < 1e-6;

            Predicate <Character> down = chara => chara.Path != null && chara.Tile != null && chara.CurrentWaypoint < chara.Path.Length &&
                                         (chara.Tile.Position - chara.Path[chara.CurrentWaypoint].Position + new Vector2(0, tileSize)).LengthSquared() < 1e-6;

            asm.AddTransition("idle down", "walking up", up);
            asm.AddTransition("idle left", "walking up", up);
            asm.AddTransition("idle right", "walking up", up);
            asm.AddTransition("idle up", "walking up", up);

            asm.AddTransition("walking down", "walking up", up);
            asm.AddTransition("walking left", "walking up", up);
            asm.AddTransition("walking right", "walking up", up);

            asm.AddTransition("idle down", "walking left", left);
            asm.AddTransition("idle left", "walking left", left);
            asm.AddTransition("idle right", "walking left", left);
            asm.AddTransition("idle up", "walking left", left);

            asm.AddTransition("walking up", "walking left", left);
            asm.AddTransition("walking down", "walking left", left);
            asm.AddTransition("walking right", "walking left", left);

            asm.AddTransition("idle down", "walking right", right);
            asm.AddTransition("idle left", "walking right", right);
            asm.AddTransition("idle right", "walking right", right);
            asm.AddTransition("idle up", "walking right", right);

            asm.AddTransition("walking up", "walking right", right);
            asm.AddTransition("walking down", "walking right", right);
            asm.AddTransition("walking left", "walking right", right);

            asm.AddTransition("idle down", "walking down", down);
            asm.AddTransition("idle left", "walking down", down);
            asm.AddTransition("idle right", "walking down", down);
            asm.AddTransition("idle up", "walking down", down);

            asm.AddTransition("walking up", "walking down", down);
            asm.AddTransition("walking left", "walking down", down);
            asm.AddTransition("walking right", "walking down", down);

            asm.AddTransition("walking down", "idle down", chara => chara.Path == null);
            asm.AddTransition("walking left", "idle left", chara => chara.Path == null);
            asm.AddTransition("walking right", "idle right", chara => chara.Path == null);
            asm.AddTransition("walking up", "idle up", chara => chara.Path == null);

            return(asm);
        }
Example #5
0
 void Start()
 {
     // Get the collisions component
     coll = GetComponent <Collisions>();
     // Get the animation state machine
     stateMachine = GetComponent <AnimationStateMachine>();
     // Set the bool to true to stop the jump dust particle playing
     jumpFinished = true;
 }
    // Use this for initialization
    void Start()
    {
        _skeletonAnimation = GetComponent <SkeletonAnimation>();
        _audioSource       = GetComponent <AudioSource>();
        _stateMachine      = new AnimationStateMachine(_skeletonAnimation);
        InitializeStates();

        _stateMachine.ChangeState(StableAnimationState.Idle);
    }
Example #7
0
    public static void AutoTransition(AnimationStateMachine animationStateMachine, AnimationState targetState, AnimationBlendData blendData, float transitionTime = 1.0f)
    {
        float animationTime = animationStateMachine.animationTime;

        if (!animationStateMachine.inTransition && animationTime > transitionTime)
        {
            animationStateMachine.SetCurrentState(targetState, blendData);
        }
    }
Example #8
0
 void Start()
 {
     // Get the components
     animationStateMachine = GetComponent <AnimationStateMachine>();
     playerController      = GetComponent <PlayerController>();
     coll      = GetComponent <Collisions>();
     wallSlide = GetComponent <WallSlide>();
     wallClimb = GetComponent <WallClimb>();
 }
Example #9
0
    public static void AutoTransition(AnimationStateMachine animationStateMachine, AnimationState targetState, float transitionDuration = 0.0f, float transitionOffset = 0.0f, float transitionTime = 1.0f)
    {
        float animationTime = animationStateMachine.animationTime;

        if (!animationStateMachine.inTransition && animationTime > transitionTime)
        {
            var blendData = new AnimationBlendData(transitionDuration, transitionOffset);
            animationStateMachine.SetCurrentState(targetState, blendData);
        }
    }
Example #10
0
        private void ActorInitializedHandler(object sender, EventArgs e)
        {
            StatefulAnimationComponent animationComponent = Owner.GetComponent <StatefulAnimationComponent>(ComponentType.Animation);

            if (animationComponent != null)
            {
                mAnimationStateMachine = animationComponent.AnimationStateMachine;
            }

            mBooster = Owner.GetBehavior <Booster>();
        }
Example #11
0
        public EnemyTest(AbstractScene scene, Vector2 position, Direction direction) : base(scene, position, direction)
        {
            AddCollisionAgainst("Spikes");
            CurrentFaceDirection = Direction.EAST;
            AnimationStateMachine animations = new AnimationStateMachine();

            animations.Offset = offset;
            AddComponent(animations);
            SpriteSheetAnimation runLeft = new SpriteSheetAnimation(this, Assets.GetTexture("EnemyRun"), 32, 32, 40);

            animations.RegisterAnimation("RunLeft", runLeft, () => Velocity.X != 0 && CurrentFaceDirection == Direction.WEST);

            SpriteSheetAnimation runRight = runLeft.CopyFlipped();

            animations.RegisterAnimation("RunRight", runRight, () => Velocity.X != 0 && CurrentFaceDirection == Direction.EAST);

            animations.AddFrameTransition("RunLeft", "RunRight");

            SpriteSheetAnimation idleLeft = new SpriteSheetAnimation(this, Assets.GetTexture("EnemyIdle"), 32, 32, 1);

            animations.RegisterAnimation("IdleLeft", idleLeft, () => Velocity.X == 0 && CurrentFaceDirection == Direction.WEST);

            SpriteSheetAnimation idleRight = idleLeft.CopyFlipped();

            animations.RegisterAnimation("IdleRight", idleRight, () => Velocity.X == 0 && CurrentFaceDirection == Direction.EAST);

            SpriteSheetAnimation jumpLeft = new SpriteSheetAnimation(this, Assets.GetTexture("EnemyRun"), 1);

            jumpLeft.StartFrame = 6;
            jumpLeft.EndFrame   = 7;
            animations.RegisterAnimation("JumpLeft", jumpLeft, () => !IsOnGround && CurrentFaceDirection == Direction.WEST, 1);

            SpriteSheetAnimation jumpRight = jumpLeft.CopyFlipped();

            animations.RegisterAnimation("JumpRight", jumpRight, () => !IsOnGround && CurrentFaceDirection == Direction.EAST, 1);

            CollisionOffsetBottom = 1;

            //AddComponent(new BoxCollisionComponent(this, 18, 30, new Vector2(-8, -30)));

            if (!Tutorial)
            {
                AddComponent(new BoxCollisionComponent(this, 18, 30, new Vector2(-8, -30)));
            }
            else
            {
                AddComponent(new BoxCollisionComponent(this, 22, 30, new Vector2(-8, -30)));
            }

            //DEBUG_SHOW_COLLIDER = true;
        }
Example #12
0
        public AbstractWeapon(AbstractScene scene, Hero owner) : base(scene.LayerManager.EntityLayer, owner, Vector2.Zero)
        {
            hero = owner;
            CurrentFaceDirection = hero.CurrentFaceDirection;
            Animations           = new AnimationStateMachine();
            AddComponent(Animations);

            if (hero.CurrentFaceDirection == Direction.EAST)
            {
                Transform.Position = RightFacingOffset;
            }
            else
            {
                Transform.Position = LeftFacingOffset;
            }
        }
        private void OnEnable()
        {
            _properties = new Properties
            {
                startState  = serializedObject.FindProperty("startState"),
                transitions = serializedObject.FindProperty("transitions"),
                clips       = serializedObject.FindProperty("transitionClips")
            };

            _contents = new Contents
            {
                animationClip = new GUIContent("Animation Clip"),
                addButton     = new GUIContent("+", "Add Transition")
            };

            targetStateMachine = (AnimationStateMachine <TState>)target;
        }
Example #14
0
 public BipedControllerComponent(Actor owner)
     : base(owner)
 {
     DesiredMovementActions = MovementActions.Neutral;
     OrientationChange      = Quaternion.Identity;
     HorizontalMovement     = Vector2.Zero;
     Controller             = null;
     MaxTurnAnglePerTick    = MathHelper.Pi / 8.0f;
     mAnimationStateMachine = null;
     mState                  = ControllerState.Neutral;
     mBooster                = null;
     AimCheck                = delegate() { return(false); };
     mAttentionLock          = new Object();
     IsAttentionAvailable    = true;
     Owner.ActorInitialized += ActorInitializedHandler;
     WorldAim                = null;
 }
Example #15
0
    public override void _Ready()
    {
        base._Ready();

        // initialize gun clips
        _leftGunAmmo  = _gunClipSize;
        _rightGunAmmo = _gunClipSize;

        // setup references for left and right state machines
        AnimationNodeBlendTree    treeRoot             = (AnimationNodeBlendTree)_animationTree.TreeRoot;
        AnimationNodeStateMachine leftMainStateMachine = (AnimationNodeStateMachine)treeRoot.GetNode("leftMainStateMachine");

        _leftMainStateMachine = new AnimationStateMachine(leftMainStateMachine, (AnimationNodeStateMachinePlayback)_animationTree.Get("parameters/leftMainStateMachine/playback"));

        AnimationNodeStateMachine rightStateMachine = (AnimationNodeStateMachine)treeRoot.GetNode("rightStateMachine");

        _rightStateMachine = new AnimationStateMachine(rightStateMachine, (AnimationNodeStateMachinePlayback)_animationTree.Get("parameters/rightStateMachine/playback"));
    }
Example #16
0
        public static Mixamo.AnimationGraph FromJson( Hashtable json_graph , AnimationStateMachine asm )
        {
            Mixamo.AnimationGraph graph = new Mixamo.AnimationGraph();
            graph.name = (string) json_graph["name"];
            graph.rootPath = (string) json_graph["root_path"];

            graph.rmSetup = new Mixamo.RootMotionSetup( asm.transform , asm.Target.transform.Find( graph.rootPath ) , asm.Target );

            ArrayList json_clips = (ArrayList) json_graph["clips"];
            graph.clips = new Mixamo.Clip[json_clips.Count];

            foreach( AnimationState s in asm.Target.animation ) {
                s.weight = 0f;
            }

            Dictionary<int , List<Clip>> sync_groups = new Dictionary<int, List<Clip>>();

            // Clips
            for( int i=0;i<json_clips.Count;i++ ) {
                Hashtable json_clip = (Hashtable)json_clips[i];
                Mixamo.Clip c = (graph.clips[i] = new Mixamo.Clip() );
                c.name = (string) json_clip["name"];
                c.type = (string) json_clip["type"];

                if( json_clip.ContainsKey("sync_clip_group" ) ) {
                    c.sync_clip_group = int.Parse( json_clip["sync_clip_group"].ToString() );
                }
                c.anim_name = (string) json_clip["anim_name"];
                //c.layer = 0;
                if( json_clip.ContainsKey( "layer" ) ) {
                    c.layer = int.Parse( json_clip["layer"].ToString() );
                } else {
                    c.layer = 0;
                }
                c.parent = graph;

                if( json_clip.ContainsKey( "root_motion_translation" ) ) {
                    switch( json_clip["root_motion_translation"].ToString() ) {
                    case "z":
                        c.RootMotion.ExtractionType = RootMotionExtractionType.Z;
                        break;
                    case "x":
                        c.RootMotion.ExtractionType = RootMotionExtractionType.X;
                        break;
                    case "y":
                        c.RootMotion.ExtractionType = RootMotionExtractionType.Y;
                        break;
                    case "xz":
                        c.RootMotion.ExtractionType = RootMotionExtractionType.XZ;
                        break;
                    case "xy":
                        c.RootMotion.ExtractionType = RootMotionExtractionType.XY;
                        break;
                    case "yz":
                        c.RootMotion.ExtractionType = RootMotionExtractionType.YZ;
                        break;
                    case "xyz":
                        c.RootMotion.ExtractionType = RootMotionExtractionType.XYZ;
                        break;
                    case "":
                        c.RootMotion.ExtractionType = RootMotionExtractionType.None;
                        break;
                    default:
                        throw new System.Exception( "Invalid Root Motion Translation Type: '" + json_clip["root_motion_translation"].ToString() + "'! Valid types: x,y,z,xy,xz,yz,xyz" );
                    }
                }

                if( json_clip.ContainsKey( "root_motion_rotation" ) && json_clip["root_motion_rotation"].ToString()  != "" ) {

                    switch( json_clip["root_motion_rotation"].ToString() ) {
                    case "x":
                        c.RootMotion.RotExtractionType = RootMotionRotExtractionType.X;
                        break;
                    case "y":
                        c.RootMotion.RotExtractionType = RootMotionRotExtractionType.Y;
                        break;
                    case "z":
                        c.RootMotion.RotExtractionType = RootMotionRotExtractionType.Z;
                        break;
                    default:
                        throw new System.Exception( "Invalid Root Motion Rotation Type: " + json_clip["root_motion_rotation"].ToString() + "! Valid types: xyz" );
                    }
                } else {
                    c.RootMotion.RotExtractionType = RootMotionRotExtractionType.None;
                }

                // setup animation state clip
                AnimationState s = asm.Target.animation[c.anim_name];
                s.wrapMode = WrapMode.Loop;
                if( c.type == "additive" )
                    s.blendMode = AnimationBlendMode.Additive;
                else
                    s.blendMode = AnimationBlendMode.Blend;
                s.layer = c.layer;
                s.weight = 0f;
                if( json_clip.ContainsKey("mixing_transform") ) {
                    Transform t = asm.Target.transform.Find( json_clip["mixing_transform"].ToString() );
                    s.AddMixingTransform( t , true);
                }
                s.enabled = true;
                c.anim_state = s;

                if( c.sync_clip_group != null ) {
                    int grp = (int)c.sync_clip_group;
                    if( !sync_groups.ContainsKey( grp ) ) {
                        sync_groups.Add( grp , new List<Clip>() );
                    }
                    sync_groups[ grp ].Add( c );
                }
            }

            // sync any layers that need to be synced together
            /*foreach( List<Clip> lst in sync_groups.Values ) {
                float sum_speed = 0;
                foreach( Clip c in lst ) {
                    sum_speed += c.anim_state.normalizedSpeed;
                }

                float avg_ns = sum_speed / lst.Count;
                foreach( Clip c in lst ) {
                    c.anim_state.normalizedSpeed = avg_ns;
                }
            }*/

            for(int i=0;i<graph.clips.Length;i++) {
                graph.clips[i].SetupRootMotionDeltas();
            }

            List<AnimationClip> clipsToDelete = new List<AnimationClip>();
            foreach( AnimationState s in asm.Target.animation ) {
                if( graph.GetClipByAnimName( s.name )  == null ) {
                    Debug.LogWarning( "Did not load the animation clip: " + s.name + ". Removing it!" );
                    clipsToDelete.Add( s.clip );
                }
            }

            foreach( AnimationClip c in clipsToDelete ) {
                asm.Target.animation.RemoveClip( c );
            }

            // Layers
            ArrayList json_layers = (ArrayList)json_graph["layers"];
            //please support more than one with this line removed!
            /*			if( json_layers.Count != 1 ) {
                throw new System.Exception( "Only supports 1 layer thus far!" );
            }*/
            graph.layers = new Mixamo.Layer[json_layers.Count];
            for( int i=0;i<json_layers.Count;i++) {
                // Layer
                Hashtable json_layer = (Hashtable)json_layers[i];
                Mixamo.Layer layer = (graph.layers[i] = new Mixamo.Layer());
                layer.name = (string)json_layer["name"];
                layer.priority = int.Parse( json_layer["priority"].ToString() );
                layer.graph = graph;

                // States
                ArrayList json_states = (ArrayList)json_layer["states"];
                layer.states = new State[json_states.Count];
                for(int j=0;j<json_states.Count;j++) {
                    // State
                    Hashtable json_state = (Hashtable)json_states[j];
                    State state = (layer.states[j] = new State());
                    state.name = (string)json_state["name"];
                    state.layer = layer;
                    state.IsLooping = json_state.ContainsKey("is_looping") ? bool.Parse( json_state["is_looping"].ToString() ) : true;
                    state.root = graph.JsonToTreeNode( (Hashtable)json_state["tree"] , state );
                }

                // Transitions
                for(int j=0;j<json_states.Count;j++ ) {
                    Hashtable json_state = (Hashtable)json_states[j];
                    State s = layer.states[j];
                    if( json_state.ContainsKey( "transitions" ) ) {
                        ArrayList json_transitions = (ArrayList) json_state["transitions"];
                        s.transitions = new Transition[ json_transitions.Count];
                        for( int k=0; k < json_transitions.Count;k++) {
                            Hashtable json_transition = (Hashtable)json_transitions[k];
                            Transition t;
                            State dest = ( json_transition["destination"].ToString() == "*" ? null : layer.GetStateByName( json_transition["destination"].ToString() ) );
                            string[] guards;
                            if( json_transition.ContainsKey( "guards" ) ) {
                                ArrayList arr = (ArrayList) json_transition["guards"];
                                guards = new string[arr.Count];
                                for(int a=0;a<arr.Count;++a) { guards[a] = arr[a].ToString(); }
                            } else {
                                guards = new string[0] {};
                            }
                            if( json_transition["type"].ToString() == "crossfade" ) {
                                t = new CrossfadeTransition( s , dest , (float)(double)json_transition["duration"] , guards );
                            } else if( json_transition["type"].ToString() == "clip" ) {
                                t = new ClipTransition( graph.GetClipByNameAndMarkInUse( json_transition["clip"].ToString() , null ) , s , dest , (float)(double) json_transition["duration_in"] , float.Parse(json_transition["duration_out"].ToString() ) , guards );
                            } else {
                                throw new System.Exception( "Transition type not supported: " + json_transition["type"] );
                            }
                            if( !s.IsLooping )
                                t.WaitTillEnd = true;
                            s.transitions[k] = t;
                        }
                    } else {
                        s.transitions = new Transition[1];
                        s.transitions[0] = layer.CreateDefaultTransition( s );
                        if( !s.IsLooping )
                            s.transitions[0].WaitTillEnd = true;
                    }
                }
            }

            graph.Init();
            return graph;
        }
Example #17
0
 public override void Release()
 {
     mAnimationStateMachine = null;
     GameResources.ActorManager.PreAnimationUpdateStep  -= PreAnimationUpdateHandler;
     GameResources.ActorManager.PostAnimationUpdateStep -= PostAnimationUpdateHandler;
 }
Example #18
0
        public static Mixamo.AnimationGraph FromJson(Hashtable json_graph, AnimationStateMachine asm)
        {
            Mixamo.AnimationGraph graph = new Mixamo.AnimationGraph();
            graph.name     = (string)json_graph["name"];
            graph.rootPath = (string)json_graph["root_path"];

            graph.rmSetup = new Mixamo.RootMotionSetup(asm.transform, asm.Target.transform.Find(graph.rootPath), asm.Target);

            ArrayList json_clips = (ArrayList)json_graph["clips"];

            graph.clips = new Mixamo.Clip[json_clips.Count];

            foreach (AnimationState s in asm.Target.GetComponent <Animation>())
            {
                s.weight = 0f;
            }

            Dictionary <int, List <Clip> > sync_groups = new Dictionary <int, List <Clip> >();

            // Clips
            for (int i = 0; i < json_clips.Count; i++)
            {
                Hashtable   json_clip = (Hashtable)json_clips[i];
                Mixamo.Clip c         = (graph.clips[i] = new Mixamo.Clip());
                c.name = (string)json_clip["name"];
                c.type = (string)json_clip["type"];

                if (json_clip.ContainsKey("sync_clip_group"))
                {
                    c.sync_clip_group = int.Parse(json_clip["sync_clip_group"].ToString());
                }
                c.anim_name = (string)json_clip["anim_name"];
                //c.layer = 0;
                if (json_clip.ContainsKey("layer"))
                {
                    c.layer = int.Parse(json_clip["layer"].ToString());
                }
                else
                {
                    c.layer = 0;
                }
                c.parent = graph;

                if (json_clip.ContainsKey("root_motion_translation"))
                {
                    switch (json_clip["root_motion_translation"].ToString())
                    {
                    case "z":
                        c.RootMotion.ExtractionType = RootMotionExtractionType.Z;
                        break;

                    case "x":
                        c.RootMotion.ExtractionType = RootMotionExtractionType.X;
                        break;

                    case "y":
                        c.RootMotion.ExtractionType = RootMotionExtractionType.Y;
                        break;

                    case "xz":
                        c.RootMotion.ExtractionType = RootMotionExtractionType.XZ;
                        break;

                    case "xy":
                        c.RootMotion.ExtractionType = RootMotionExtractionType.XY;
                        break;

                    case "yz":
                        c.RootMotion.ExtractionType = RootMotionExtractionType.YZ;
                        break;

                    case "xyz":
                        c.RootMotion.ExtractionType = RootMotionExtractionType.XYZ;
                        break;

                    case "":
                        c.RootMotion.ExtractionType = RootMotionExtractionType.None;
                        break;

                    default:
                        throw new System.Exception("Invalid Root Motion Translation Type: '" + json_clip["root_motion_translation"].ToString() + "'! Valid types: x,y,z,xy,xz,yz,xyz");
                    }
                }

                if (json_clip.ContainsKey("root_motion_rotation") && json_clip["root_motion_rotation"].ToString() != "")
                {
                    switch (json_clip["root_motion_rotation"].ToString())
                    {
                    case "x":
                        c.RootMotion.RotExtractionType = RootMotionRotExtractionType.X;
                        break;

                    case "y":
                        c.RootMotion.RotExtractionType = RootMotionRotExtractionType.Y;
                        break;

                    case "z":
                        c.RootMotion.RotExtractionType = RootMotionRotExtractionType.Z;
                        break;

                    default:
                        throw new System.Exception("Invalid Root Motion Rotation Type: " + json_clip["root_motion_rotation"].ToString() + "! Valid types: xyz");
                    }
                }
                else
                {
                    c.RootMotion.RotExtractionType = RootMotionRotExtractionType.None;
                }

                // setup animation state clip
                AnimationState s = asm.Target.GetComponent <Animation>()[c.anim_name];
                s.wrapMode = WrapMode.Loop;
                if (c.type == "additive")
                {
                    s.blendMode = AnimationBlendMode.Additive;
                }
                else
                {
                    s.blendMode = AnimationBlendMode.Blend;
                }
                s.layer  = c.layer;
                s.weight = 0f;
                if (json_clip.ContainsKey("mixing_transform"))
                {
                    Transform t = asm.Target.transform.Find(json_clip["mixing_transform"].ToString());
                    s.AddMixingTransform(t, true);
                }
                s.enabled    = true;
                c.anim_state = s;

                if (c.sync_clip_group != null)
                {
                    int grp = (int)c.sync_clip_group;
                    if (!sync_groups.ContainsKey(grp))
                    {
                        sync_groups.Add(grp, new List <Clip>());
                    }
                    sync_groups[grp].Add(c);
                }
            }

            // sync any layers that need to be synced together

            /*foreach( List<Clip> lst in sync_groups.Values ) {
             *      float sum_speed = 0;
             *      foreach( Clip c in lst ) {
             *              sum_speed += c.anim_state.normalizedSpeed;
             *      }
             *
             *      float avg_ns = sum_speed / lst.Count;
             *      foreach( Clip c in lst ) {
             *              c.anim_state.normalizedSpeed = avg_ns;
             *      }
             * }*/


            for (int i = 0; i < graph.clips.Length; i++)
            {
                graph.clips[i].SetupRootMotionDeltas();
            }

            List <AnimationClip> clipsToDelete = new List <AnimationClip>();

            foreach (AnimationState s in asm.Target.GetComponent <Animation>())
            {
                if (graph.GetClipByAnimName(s.name) == null)
                {
                    Debug.LogWarning("Did not load the animation clip: " + s.name + ". Removing it!");
                    clipsToDelete.Add(s.clip);
                }
            }


            foreach (AnimationClip c in clipsToDelete)
            {
                asm.Target.GetComponent <Animation>().RemoveClip(c);
            }


            // Layers
            ArrayList json_layers = (ArrayList)json_graph["layers"];

            //please support more than one with this line removed!

/*			if( json_layers.Count != 1 ) {
 *                              throw new System.Exception( "Only supports 1 layer thus far!" );
 *                      }*/
            graph.layers = new Mixamo.Layer[json_layers.Count];
            for (int i = 0; i < json_layers.Count; i++)
            {
                // Layer
                Hashtable    json_layer = (Hashtable)json_layers[i];
                Mixamo.Layer layer      = (graph.layers[i] = new Mixamo.Layer());
                layer.name     = (string)json_layer["name"];
                layer.priority = int.Parse(json_layer["priority"].ToString());
                layer.graph    = graph;

                // States
                ArrayList json_states = (ArrayList)json_layer["states"];
                layer.states = new State[json_states.Count];
                for (int j = 0; j < json_states.Count; j++)
                {
                    // State
                    Hashtable json_state = (Hashtable)json_states[j];
                    State     state      = (layer.states[j] = new State());
                    state.name      = (string)json_state["name"];
                    state.layer     = layer;
                    state.IsLooping = json_state.ContainsKey("is_looping") ? bool.Parse(json_state["is_looping"].ToString()) : true;
                    state.root      = graph.JsonToTreeNode((Hashtable)json_state["tree"], state);
                }

                // Transitions
                for (int j = 0; j < json_states.Count; j++)
                {
                    Hashtable json_state = (Hashtable)json_states[j];
                    State     s          = layer.states[j];
                    if (json_state.ContainsKey("transitions"))
                    {
                        ArrayList json_transitions = (ArrayList)json_state["transitions"];
                        s.transitions = new Transition[json_transitions.Count];
                        for (int k = 0; k < json_transitions.Count; k++)
                        {
                            Hashtable  json_transition = (Hashtable)json_transitions[k];
                            Transition t;
                            State      dest = (json_transition["destination"].ToString() == "*" ? null : layer.GetStateByName(json_transition["destination"].ToString()));
                            string[]   guards;
                            if (json_transition.ContainsKey("guards"))
                            {
                                ArrayList arr = (ArrayList)json_transition["guards"];
                                guards = new string[arr.Count];
                                for (int a = 0; a < arr.Count; ++a)
                                {
                                    guards[a] = arr[a].ToString();
                                }
                            }
                            else
                            {
                                guards = new string[0] {
                                };
                            }
                            if (json_transition["type"].ToString() == "crossfade")
                            {
                                t = new CrossfadeTransition(s, dest, (float)(double)json_transition["duration"], guards);
                            }
                            else if (json_transition["type"].ToString() == "clip")
                            {
                                t = new ClipTransition(graph.GetClipByNameAndMarkInUse(json_transition["clip"].ToString(), null), s, dest, (float)(double)json_transition["duration_in"], float.Parse(json_transition["duration_out"].ToString()), guards);
                            }
                            else
                            {
                                throw new System.Exception("Transition type not supported: " + json_transition["type"]);
                            }
                            if (!s.IsLooping)
                            {
                                t.WaitTillEnd = true;
                            }
                            s.transitions[k] = t;
                        }
                    }
                    else
                    {
                        s.transitions    = new Transition[1];
                        s.transitions[0] = layer.CreateDefaultTransition(s);
                        if (!s.IsLooping)
                        {
                            s.transitions[0].WaitTillEnd = true;
                        }
                    }
                }
            }

            graph.Init();
            return(graph);
        }
Example #19
0
 private void AnimationUpdateHandler(object sender, UpdateStepEventArgs e)
 {
     AnimationStateMachine.Update(e.GameTime);
 }
Example #20
0
 public void Initialize(IEntity ownerEntity)
 {
     ASMachine = new AnimationStateMachine();
     ASMachine.Initialize(_owner);
 }
Example #21
0
    public override void Init(int heroIndex, CreatureStateEnum defaultState)
    {
        Init(heroIndex);
        m_stateMachine = new AnimationStateMachine(9, m_animation);
        m_blockFinder  = new MainHeroBlockFinder(this);
        m_damageRunner = Singleton <HeroTeamRunner> .Instance.GetOrCreateHeroDamageRunner(0);

        m_raycastMask = 1 << LayerMask.NameToLayer("Blocks");
        AnimState animState = new AnimState(0);

        animState.AnimationNames = new string[1]
        {
            "Enter"
        };
        animState.Looping = false;
        animState.Speed.Set(0.9f, 1.1f);
        animState.Enter = delegate
        {
            m_blockFinder.Clear();
            base.transform.position       = GetEnterPosition();
            m_stateMachine.Skeleton.FlipX = false;
            AudioController.Instance.QueueEvent(new AudioEvent(m_audioEventEnter, AUDIOEVENTACTION.Play));
        };
        animState.AnimComplete = EnterComplete;
        m_stateMachine.Add(animState);
        AnimState animState2 = new AnimState(1);

        animState2.AnimationNames = new string[4]
        {
            "Idle1",
            "Idle2",
            "Idle3",
            "Idle4"
        };
        animState2.Looping = true;
        animState2.Speed.Set(0.9f, 1.1f);
        animState2.Enter = delegate
        {
            m_stateMachine.Skeleton.FlipX = false;
        };
        animState2.Step = StepIdle;
        m_stateMachine.Add(animState2);
        AnimState animState3 = new AnimState(3);

        animState3.AnimationNames = new string[4]
        {
            "Idle1",
            "Idle2",
            "Idle3",
            "Idle4"
        };
        animState3.Looping = true;
        animState3.Speed.Set(0.9f, 1.1f);
        animState3.Enter = delegate
        {
            m_stateMachine.Skeleton.FlipX = false;
        };
        m_stateMachine.Add(animState3);
        AnimState animState4 = new AnimState(2);

        animState4.AnimationNames = new string[1]
        {
            "Cheering"
        };
        animState4.Looping = true;
        animState4.Speed.Set(0.9f, 1.1f);
        animState4.Enter = delegate
        {
            m_stateMachine.Skeleton.FlipX = false;
            AudioController.Instance.QueueEvent(new AudioEvent(m_audioEventCheer, AUDIOEVENTACTION.Play));
        };
        animState4.Exit = delegate
        {
            AudioController.Instance.QueueEvent(new AudioEvent(m_audioEventCheer, AUDIOEVENTACTION.Stop));
        };
        m_stateMachine.Add(animState4);
        AnimState animState5 = new AnimState(4);

        animState5.AnimationNames = new string[1]
        {
            "Move"
        };
        animState5.Looping = true;
        animState5.Speed.Set(0.9f, 1.1f);
        animState5.Enter = delegate
        {
            Vector3 vector = GetWantedPosition() - base.transform.position;
            m_stateMachine.Skeleton.FlipX = (vector.x + vector.z * 0.5f < 0f);
        };
        animState5.Step = StepMove;
        m_stateMachine.Add(animState5);
        AnimState animState6 = new AnimState(5);

        animState6.AnimationNames = new string[5]
        {
            "Attack1",
            "Attack2",
            "Attack3",
            "Attack4",
            "Attack5"
        };
        animState6.Looping = true;
        animState6.Speed.Set(0.9f, 1.1f);
        animState6.Enter = delegate
        {
            m_stateMachine.Skeleton.FlipX = false;
        };
        animState6.AnimComplete = AttackComplete;
        animState6.AnimEvent    = AttackEvent;
        animState6.Step         = AttackStep;
        m_stateMachine.Add(animState6);
        AnimState animState7 = new AnimState(7);

        animState7.AnimationNames = new string[1]
        {
            "Attack6"
        };
        animState7.Looping = true;
        animState7.Speed.Set(0.9f, 1.1f);
        animState7.Enter = delegate
        {
            m_stateMachine.Skeleton.FlipX = false;
        };
        animState7.AnimComplete = AttackComplete;
        animState7.AnimEvent    = AttackEvent;
        m_stateMachine.Add(animState7);
        m_stateMachine.NextState = (int)defaultState;
        PlayerData.Instance.MainChunk.Subscribe(delegate
        {
            m_blockFinder.Clear();
        }).AddTo(this);
        (from pair in Singleton <CameraMoveRunner> .Instance.IsCameraMoving.Pairwise()
         select pair.Previous&& !pair.Current into cameraStopped
         where cameraStopped
         select cameraStopped).Subscribe(delegate
        {
            m_stateMachine.NextState = 0;
        }).AddTo(this);
        Singleton <ChunkRunner> .Instance.BlocksClearTriggered.Subscribe(delegate
        {
            m_stateMachine.NextState = 3;
        }).AddTo(this);

        (from win in Singleton <BossBattleRunner> .Instance.BossBattleResult.Skip(1)
         where win
         select win).Subscribe(delegate
        {
            m_stateMachine.NextState = 2;
        }).AddTo(this);
        Singleton <ChunkRunner> .Instance.ChapterCompleted.Subscribe(delegate
        {
            m_stateMachine.NextState = 0;
        }).AddTo(this);

        (from active in Singleton <HammerTimeRunner> .Instance.Active.DelayFrame(1)
         select(!active) ? "Common" : "Gold").Subscribe(delegate(string skin)
        {
            m_animation.skeleton.SetSkin(skin);
            m_animation.skeleton.SetSlotsToSetupPose();
            m_animation.AnimationState.Apply(m_animation.skeleton);
        }).AddTo(this);
    }
Example #22
0
    private void Init()
    {
        m_animation    = GetComponentInChildren <SkeletonAnimation>();
        m_stateMachine = new AnimationStateMachine(5, m_animation);
        AnimState animState = new AnimState(0);

        animState.AnimationNames = new string[1]
        {
            "DrJelly_Entry"
        };
        animState.Looping = false;
        animState.Speed.Set(0.9f, 1.1f);
        animState.Enter = delegate
        {
            m_stateMachine.Skeleton.FlipX = false;
        };
        animState.MixDuration  = 0f;
        animState.AnimComplete = EnterComplete;
        m_stateMachine.Add(animState);
        AnimState animState2 = new AnimState(1);

        animState2.AnimationNames = new string[1]
        {
            "DrJelly_Idle"
        };
        animState2.Looping = true;
        animState2.Speed.Set(0.9f, 1.1f);
        animState2.Enter = delegate
        {
            m_stateMachine.Skeleton.FlipX = false;
        };
        animState2.MixDuration = 0.5f;
        m_stateMachine.Add(animState2);
        AnimState animState3 = new AnimState(2);

        animState3.AnimationNames = new string[1]
        {
            "DrJelly_Exit"
        };
        animState3.Looping = false;
        animState3.Speed.Set(0.9f, 1.1f);
        animState3.Enter = delegate
        {
            m_stateMachine.Skeleton.FlipX = false;
        };
        animState3.MixDuration = 0.5f;
        m_stateMachine.Add(animState3);
        AnimState animState4 = new AnimState(3);

        animState4.AnimationNames = new string[1]
        {
            "_Shooting"
        };
        animState4.Looping = false;
        animState4.Speed.Set(0.9f, 1.1f);
        animState4.Enter = delegate
        {
            m_stateMachine.Skeleton.FlipX = false;
        };
        animState4.AnimComplete = ShootingComplete;
        animState4.MixDuration  = 0.5f;
        m_stateMachine.Add(animState4);
        AnimState animState5 = new AnimState(4);

        animState5.AnimationNames = new string[1]
        {
            "HitEffect"
        };
        animState5.Looping = false;
        animState5.Speed.Set(0.9f, 1.1f);
        animState5.Enter = delegate
        {
            m_stateMachine.Skeleton.FlipX = false;
        };
        m_stateMachine.Add(animState5);
        m_stateMachine.NextState = 0;
        Singleton <BossBattleRunner> .Instance.BossBattleResult.Skip(1).Subscribe(delegate
        {
            m_stateMachine.NextState = 2;
        }).AddTo(this);

        (from hp in Singleton <BossBattleRunner> .Instance.BossCurrentHP.ThrottleFirst(TimeSpan.FromSeconds(0.2)).Pairwise()
         where hp.Current < hp.Previous
         select hp).Subscribe(delegate
        {
            GetHit();
        }).AddTo(this);
    }
Example #23
0
    // Update is called once per frame
    void Update()
    {
        //Apply gravity
        moveDirection.y = controller.velocity.y - gravity * Time.deltaTime;

        AnimationStateMachine asm = GetASM();
        int turnDirection         = 0;

        if (Input.GetKey(KeyCode.W))
        {
            if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
            {
                asm.ControlWeights["ctrl_move"] = Mixamo.Util.CrossFadeDown(asm.ControlWeights["ctrl_move"], 0.3f);
            }
            else
            {
                asm.ControlWeights["ctrl_move"] = Mixamo.Util.CrossFadeUp(asm.ControlWeights["ctrl_move"], 0.3f);
            }
            asm.ChangeState("move");
        }
        else if (Input.GetKey(KeyCode.S))
        {
            if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
            {
                asm.ChangeState("run_backwards");
            }

            else
            {
                asm.ChangeState("walk_backwards");
            }
        }
        else if (Input.GetKey(KeyCode.A))
        {
            if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
            {
                asm.ChangeState("strafe_left");
            }

            else
            {
                asm.ChangeState("walk_strafe_left");
            }
        }

        else if (Input.GetKey(KeyCode.D))
        {
            if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
            {
                asm.ChangeState("strafe_right");
            }

            else
            {
                asm.ChangeState("walk_strafe_right");
            }
        }

        else if (Input.GetKey(KeyCode.Q))
        {
            asm.ChangeState("turn_left");
        }
        else if (Input.GetKey(KeyCode.E))
        {
            asm.ChangeState("turn_right");
        }


        else
        {
            asm.ChangeState(0, "idle");
        }

        if (Input.GetKey(KeyCode.Space))
        {
            asm.ChangeState("jump");
        }


        if (Input.GetKey(KeyCode.Q))
        {
            turnDirection = -1;
        }
        else if (Input.GetKey(KeyCode.E))
        {
            turnDirection = 1;
        }

        if (turnDirection != 0f)
        {
            Vector3 forward = this.transform.forward;
            forward.y = 0;
            forward   = forward.normalized;
            Vector3 right = new Vector3(forward.z, 0, -forward.x);
            transform.rotation = Quaternion.LookRotation(Vector3.RotateTowards(forward, right * turnDirection, turnDegrees * Mathf.Deg2Rad * Time.deltaTime, 1000f));
        }
    }
Example #24
0
    // Update is called once per frame
    void Update()
    {
        //Apply gravity
        moveDirection.y = controller.velocity.y - gravity * Time.deltaTime;

        AnimationStateMachine asm = GetASM();
        int turnDirection         = 0;

        if (Input.GetKey(KeyCode.W))
        {
            if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
            {
                asm.ControlWeights["ctrl_move"] = Mixamo.Util.CrossFadeDown(asm.ControlWeights["ctrl_move"], 0.3f);
            }
            else
            {
                asm.ControlWeights["ctrl_move"] = Mixamo.Util.CrossFadeUp(asm.ControlWeights["ctrl_move"], 0.3f);
            }
            asm.ChangeState("move");
        }
        else if (Input.GetKey(KeyCode.S))
        {
            if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
            {
                asm.ChangeState("run_backwards");
            }

            else
            {
                asm.ChangeState("walk_backwards");
            }
        }
        else if (Input.GetKey(KeyCode.A))
        {
            if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
            {
                asm.ChangeState("strafe_left");
            }

            else
            {
                asm.ChangeState("walk_strafe_left");
            }
        }

        else if (Input.GetKey(KeyCode.D))
        {
            if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
            {
                asm.ChangeState("strafe_right");
            }

            else
            {
                asm.ChangeState("walk_strafe_right");
            }
        }

        else if (Input.GetKey(KeyCode.Q))
        {
            asm.ChangeState("turn_left");
        }
        else if (Input.GetKey(KeyCode.E))
        {
            asm.ChangeState("turn_right");
        }


        else
        {
            asm.ChangeState(0, "idle");
        }


        // Upperbody Layer Controls that change based on the states above. Working along the same logic, if the player is crouched
        // The states the play are the states available to a crouching player.
        if (upperbodyLayer)
        {
            if (Input.GetKeyDown(KeyCode.R))
            {
                asm.ChangeState(1, "reload");
            }
            if (Input.GetButton("Fire1"))
            {
                asm.ChangeState(1, "fire");
            }
            else
            {
                asm.ChangeState(1, "nothing");
            }       if (Input.GetKeyDown(KeyCode.F))
            {
                asm.ChangeState(1, "granade");
            }
            if (Input.GetKeyDown(KeyCode.H))
            {
                asm.ChangeState(1, "hitreaction");
            }
        }

        if (Input.GetKey(KeyCode.Q))
        {
            turnDirection = -1;
        }
        else if (Input.GetKey(KeyCode.E))
        {
            turnDirection = 1;
        }

        if (turnDirection != 0f)
        {
            Vector3 forward = this.transform.forward;
            forward.y = 0;
            forward   = forward.normalized;
            Vector3 right = new Vector3(forward.z, 0, -forward.x);
            transform.rotation = Quaternion.LookRotation(Vector3.RotateTowards(forward, right * turnDirection, turnDegrees * Mathf.Deg2Rad * Time.deltaTime, 1000f));
        }
    }
Example #25
0
        public Hero(AbstractScene scene, Vector2 position) : base(scene.LayerManager.EntityLayer, null, position)
        {
            //DEBUG_SHOW_PIVOT = true;

            AddTag("Hero");
            AddCollisionAgainst("Enemy");
            AddCollisionAgainst("Spikes");
            AddCollisionAgainst("Trap");

            CanFireTriggers = true;

            DrawPriority = 10;

            AddCollisionAgainst("Pickup");
            AddCollisionAgainst("Door", false);
            AddCollisionAgainst("Key");
            AddCollisionAgainst("MountedGunBullet");

            SetupController();

            CollisionOffsetBottom = 1;
            CollisionOffsetLeft   = 0.5f;
            CollisionOffsetRight  = 0.5f;
            CollisionOffsetTop    = 1;

            CurrentFaceDirection = Direction.EAST;

            collisionComponent = new BoxCollisionComponent(this, 18, 30, new Vector2(-8, -30));
            AddComponent(collisionComponent);
            //DEBUG_SHOW_COLLIDER = true;

            AnimationStateMachine animations = new AnimationStateMachine();

            animations.Offset = offset;
            AddComponent(animations);

            SpriteSheetAnimation idleLeft = new SpriteSheetAnimation(this, Assets.GetTexture("HeroIdle"), 24);

            /*idleLeft.AnimationSwitchCallback = () => { if (CurrentWeapon != null) CurrentWeapon.SetAnimationBreathingOffset(Vector2.Zero); };
             * idleLeft.EveryFrameAction = (frame) =>
             *  {
             *      if (CurrentWeapon == null) return;
             *      float unit = 0.5f;
             *      float offsetY = 0;
             *      if (frame == 2 || frame == 3 || frame == 4)
             *      {
             *          offsetY += unit;
             *      }
             *      else if (frame == 6 || frame == 7)
             *      {
             *          offsetY -= unit;
             *      }
             *      CurrentWeapon.SetAnimationBreathingOffset(new Vector2(0, offsetY));
             *  };*/
            idleLeft.StartedCallback = () =>
            {
                if (CurrentWeapon == null)
                {
                    return;
                }
                if (CurrentWeapon is Shotgun)
                {
                    (CurrentWeapon as Handgun).SetLeftFacingOffset(new Vector2(-3, -17));
                    (CurrentWeapon as Handgun).SetRightFacingOffset(new Vector2(3, -17));
                }
                else if (CurrentWeapon is Machinegun)
                {
                    (CurrentWeapon as Handgun).SetLeftFacingOffset(new Vector2(-3, -17));
                    (CurrentWeapon as Handgun).SetRightFacingOffset(new Vector2(3, -17));
                }
                else if (CurrentWeapon is Handgun)
                {
                    (CurrentWeapon as Handgun).SetLeftFacingOffset(new Vector2(-3, -17));
                    (CurrentWeapon as Handgun).SetRightFacingOffset(new Vector2(3, -17));
                }
            };
            animations.RegisterAnimation("IdleLeft", idleLeft, () => previousPosition == Transform.Position && CurrentFaceDirection == Direction.WEST);

            SpriteSheetAnimation idleRight = idleLeft.CopyFlipped();

            animations.RegisterAnimation("IdleRight", idleRight, () => previousPosition == Transform.Position && CurrentFaceDirection == Direction.EAST);

            SpriteSheetAnimation runLeft = new SpriteSheetAnimation(this, Assets.GetTexture("HeroRun"), 40);

            runLeft.StartedCallback = () =>
            {
                if (CurrentWeapon == null)
                {
                    return;
                }
                if (CurrentWeapon is Shotgun)
                {
                    (CurrentWeapon as Handgun).SetLeftFacingOffset(new Vector2(-3, -17));
                    (CurrentWeapon as Handgun).SetRightFacingOffset(new Vector2(3, -17));
                }
                else if (CurrentWeapon is Machinegun)
                {
                    (CurrentWeapon as Handgun).SetLeftFacingOffset(new Vector2(-3, -17));
                    (CurrentWeapon as Handgun).SetRightFacingOffset(new Vector2(3, -17));
                }
                else if (CurrentWeapon is Handgun)
                {
                    (CurrentWeapon as Handgun).SetLeftFacingOffset(new Vector2(1, -17));
                    (CurrentWeapon as Handgun).SetRightFacingOffset(new Vector2(-1, -17));
                }
            };
            animations.RegisterAnimation("RunLeft", runLeft, () => Velocity.X < 0 && CurrentFaceDirection == Direction.WEST);

            SpriteSheetAnimation runRight = runLeft.CopyFlipped();

            animations.RegisterAnimation("RunRight", runRight, () => Velocity.X > 0 && CurrentFaceDirection == Direction.EAST);

            SpriteSheetAnimation runBackwardsLeft = new SpriteSheetAnimation(this, Assets.GetTexture("HeroRunBackwards"), 40);

            runBackwardsLeft.StartedCallback = () =>
            {
                if (CurrentWeapon == null)
                {
                    return;
                }
                if (CurrentWeapon is Shotgun)
                {
                    (CurrentWeapon as Handgun).SetLeftFacingOffset(new Vector2(-3, -17));
                    (CurrentWeapon as Handgun).SetRightFacingOffset(new Vector2(3, -17));
                }
                else if (CurrentWeapon is Machinegun)
                {
                    (CurrentWeapon as Handgun).SetLeftFacingOffset(new Vector2(-3, -17));
                    (CurrentWeapon as Handgun).SetRightFacingOffset(new Vector2(3, -17));
                }
                else if (CurrentWeapon is Handgun)
                {
                    (CurrentWeapon as Handgun).SetLeftFacingOffset(new Vector2(1, -17));
                    (CurrentWeapon as Handgun).SetRightFacingOffset(new Vector2(-1, -17));
                }
            };
            animations.RegisterAnimation("RunBackwardsLeft", runBackwardsLeft, () => Velocity.X > 0 && CurrentFaceDirection == Direction.WEST);

            SpriteSheetAnimation runRighrunBackwardsRight = runBackwardsLeft.CopyFlipped();

            animations.RegisterAnimation("RunBackwardsRight", runRighrunBackwardsRight, () => Velocity.X < 0 && CurrentFaceDirection == Direction.EAST);

            SpriteSheetAnimation jumpLeft = new SpriteSheetAnimation(this, Assets.GetTexture("HeroRun"), 1);

            jumpLeft.StartFrame = 6;
            jumpLeft.EndFrame   = 7;
            animations.RegisterAnimation("JumpLeft", jumpLeft, () => !IsOnGround && CurrentFaceDirection == Direction.WEST, 1);

            SpriteSheetAnimation jumpRight = jumpLeft.CopyFlipped();

            animations.RegisterAnimation("JumpRight", jumpRight, () => !IsOnGround && CurrentFaceDirection == Direction.EAST, 1);

            SpriteSheetAnimation jetpackLeft = new SpriteSheetAnimation(this, Assets.GetTexture("Jetpacking"), 40);

            animations.RegisterAnimation("JetpackLeft", jetpackLeft, () => flying && CurrentFaceDirection == Direction.WEST, 2);

            SpriteSheetAnimation jetpackRight = jetpackLeft.CopyFlipped();

            animations.RegisterAnimation("JetpackRight", jetpackRight, () => flying && CurrentFaceDirection == Direction.EAST, 2);

            SpriteSheetAnimation kickLeft = new SpriteSheetAnimation(this, Assets.GetTexture("Kick"), 40);

            kickLeft.Looping = false;
            kickLeft.AddFrameAction(5, (frame) =>
            {
                AudioEngine.Play("Kick");
                IsKicking = true;
                if (THIS_IS_SPARTAAAAA && collidingWith.Count > 0)
                {
                    THIS_IS_SPARTAAAAA    = false;
                    Vector2 canSpawnPos   = collidingWith[0].Transform.Position;
                    FuelCan can           = new FuelCan(scene, canSpawnPos + new Vector2(0, -20), TankCapacity);
                    can.Velocity         += new Vector2(-3, -1);
                    can.CollisionsEnabled = false;

                    Ammo ammo              = new Ammo(scene, canSpawnPos + new Vector2(0, -20), 20, typeof(Handgun));
                    ammo.Velocity         += new Vector2(-4f, -1.5f);
                    ammo.CollisionsEnabled = false;
                    Timer.TriggerAfter(2000, () =>
                    {
                        can.CollisionsEnabled  = true;
                        ammo.CollisionsEnabled = true;

                        new TextPopup(Scene, Assets.GetTexture("FuelAmmoText"), Transform.Position + new Vector2(-20, -80), 0.3f, 3000);
                    });
                }
            });
            kickLeft.AddFrameAction(6, (frame) =>
            {
                IsKicking = false;
            });
            kickLeft.StartedCallback = () =>
            {
                if (THIS_IS_SPARTAAAAA && collidingWith.Count > 0)
                {
                    THIS_IS_SPARTA();
                    Globals.FixedUpdateMultiplier = 0.1f;
                    Timer.TriggerAfter(3000, () =>
                    {
                        Globals.FixedUpdateMultiplier = 0.5f;

                        Timer.Repeat(1000, (elapsedTime) =>
                        {
                            Scene.Camera.Zoom -= 0.002f * elapsedTime;
                        });
                    });
                }
                //IsKicking = true;
                if (IsOnGround)
                {
                    MovementSpeed = 0;
                }

                if (CurrentWeapon == null)
                {
                    return;
                }
                if (CurrentWeapon is Shotgun)
                {
                    (CurrentWeapon as Handgun).SetLeftFacingOffset(new Vector2(-3, -17));
                    (CurrentWeapon as Handgun).SetRightFacingOffset(new Vector2(3, -17));
                }
                else if (CurrentWeapon is Machinegun)
                {
                    (CurrentWeapon as Handgun).SetLeftFacingOffset(new Vector2(-3, -17));
                    (CurrentWeapon as Handgun).SetRightFacingOffset(new Vector2(3, -17));
                }
                else if (CurrentWeapon is Handgun)
                {
                    (CurrentWeapon as Handgun).SetLeftFacingOffset(new Vector2(1, -17));
                    (CurrentWeapon as Handgun).SetRightFacingOffset(new Vector2(-1, -17));
                }
            };

            kickLeft.AnimationSwitchCallback = () =>
            {
                IsKicking     = false;
                MovementSpeed = Config.CHARACTER_SPEED;
                foreach (AbstractEnemy enemy in collidingWith)
                {
                    enemy.IsKicked = false;
                }
            };
            animations.RegisterAnimation("KickLeft", kickLeft, () => false);

            SpriteSheetAnimation kickRight = kickLeft.CopyFlipped();

            animations.RegisterAnimation("KickRight", kickRight, () => false);

            SpriteSheetAnimation kickJetpackLeft = new SpriteSheetAnimation(this, Assets.GetTexture("KickJetpacking"), 40);

            kickJetpackLeft.Looping = false;
            kickJetpackLeft.AddFrameAction(5, (frame) =>
            {
                AudioEngine.Play("Kick");
                IsKicking = true;
            });
            kickJetpackLeft.AddFrameAction(6, (frame) =>
            {
                IsKicking = false;
            });
            kickJetpackLeft.StartedCallback = () =>
            {
                //IsKicking = true;
                if (CurrentWeapon == null)
                {
                    return;
                }
                if (CurrentWeapon is Shotgun)
                {
                    (CurrentWeapon as Handgun).SetLeftFacingOffset(new Vector2(-3, -17));
                    (CurrentWeapon as Handgun).SetRightFacingOffset(new Vector2(3, -17));
                }
                else if (CurrentWeapon is Machinegun)
                {
                    (CurrentWeapon as Handgun).SetLeftFacingOffset(new Vector2(-3, -17));
                    (CurrentWeapon as Handgun).SetRightFacingOffset(new Vector2(3, -17));
                }
                else if (CurrentWeapon is Handgun)
                {
                    (CurrentWeapon as Handgun).SetLeftFacingOffset(new Vector2(1, -17));
                    (CurrentWeapon as Handgun).SetRightFacingOffset(new Vector2(-1, -17));
                }
            };
            kickJetpackLeft.AnimationSwitchCallback = () =>
            {
                IsKicking = false;
            };
            animations.RegisterAnimation("KickJetpackLeft", kickJetpackLeft, () => false);

            SpriteSheetAnimation kickJetpackRight = kickJetpackLeft.CopyFlipped();

            animations.RegisterAnimation("KickJetpackRight", kickJetpackRight, () => false);

            animations.AddFrameTransition("RunLeft", "RunBackwardsLeft");
            animations.AddFrameTransition("RunRight", "RunBackwardsRight");
            animations.AddFrameTransition("RunLeft", "RunRight");
            animations.AddFrameTransition("RunBackwardsLeft", "RunBackwardsRight");
            animations.AddFrameTransition("JetpackLeft", "JetpackRight");

            Visible = true;
            Active  = true;

            /*DebugFunction = () =>
             * {
             *  return "Fuel: " + (int)(((float)(Fuel / TankCapacity)) * 100) + " %";
             * };*/

            CurrentWeapon = new Handgun(scene, this);
            weapons.Add(CurrentWeapon);
            Machinegun mg = new Machinegun(scene, this);

            mg.Visible = false;
            Shotgun sg = new Shotgun(scene, this);

            sg.Visible = false;
            weapons.Add(mg);
            weapons.Add(sg);
        }
Example #26
0
 public abstract void InitAnimation(AnimationStateMachine animationStateMachine);
Example #27
0
 // Let Transition Handler know that this is the object it should be watching for transition information
 void Start()
 {
     GetASM().SetTransitionHandler( this );
     controller = GetComponent<CharacterController>();
     asm = GetASM();
 }
Example #28
0
 protected override void CreateAnimationPlayer(AnimationPackage animationPackage)
 {
     AnimationStateMachine = new AnimationStateMachine(animationPackage);
     GameResources.ActorManager.AnimationUpdateStep += AnimationUpdateHandler;
 }
Example #29
0
    public override void Init(int heroIndex, CreatureStateEnum defaultState)
    {
        Init(heroIndex);
        m_stateMachine   = new AnimationStateMachine(9, m_animation);
        m_blockFinder    = new CreatureBlockFinder(this);
        m_projectileBone = m_stateMachine.Skeleton.FindBone("root");
        AnimState animState = new AnimState(0);

        animState.AnimationNames = new string[1]
        {
            "Enter"
        };
        animState.Looping = false;
        animState.Speed.Set(0.9f, 1.1f);
        animState.Enter = delegate
        {
            m_blockFinder.Clear();
            base.transform.position       = GetEnterPosition();
            m_stateMachine.Skeleton.FlipX = false;
            AudioController.Instance.QueueEvent(new AudioEvent(m_audioEventEnter, AUDIOEVENTACTION.Play));
        };
        animState.AnimComplete = EnterComplete;
        m_stateMachine.Add(animState);
        AnimState animState2 = new AnimState(1);

        animState2.AnimationNames = new string[1]
        {
            "Idle"
        };
        animState2.Looping = true;
        animState2.Speed.Set(0.9f, 1.1f);
        animState2.Enter = delegate
        {
            m_stateMachine.Skeleton.FlipX = false;
        };
        animState2.Step = StepIdle;
        m_stateMachine.Add(animState2);
        AnimState animState3 = new AnimState(3);

        animState3.AnimationNames = new string[1]
        {
            "Idle"
        };
        animState3.Looping = true;
        animState3.Speed.Set(0.9f, 1.1f);
        animState3.Enter = delegate
        {
            m_stateMachine.Skeleton.FlipX = false;
        };
        m_stateMachine.Add(animState3);
        AnimState animState4 = new AnimState(2);

        animState4.AnimationNames = new string[1]
        {
            "Cheering"
        };
        animState4.Looping = true;
        animState4.Speed.Set(0.9f, 1.1f);
        animState4.Enter = delegate
        {
            m_stateMachine.Skeleton.FlipX = false;
            AudioController.Instance.QueueEvent(new AudioEvent(m_audioEventCheer, AUDIOEVENTACTION.Play));
        };
        animState4.Exit = delegate
        {
            AudioController.Instance.QueueEvent(new AudioEvent(m_audioEventCheer, AUDIOEVENTACTION.Stop));
        };
        m_stateMachine.Add(animState4);
        AnimState animState5 = new AnimState(4);

        animState5.AnimationNames = new string[1]
        {
            "Move"
        };
        animState5.Looping = true;
        animState5.Speed.Set(1.53f, 1.87000012f);
        animState5.Enter = delegate
        {
            Vector3 vector = GetWantedPosition() - base.transform.position;
            m_stateMachine.Skeleton.FlipX = (vector.x + vector.z * 0.5f < 0f);
        };
        animState5.Step = StepMove;
        m_stateMachine.Add(animState5);
        AnimState animState6 = new AnimState(5);

        animState6.AnimationNames = new string[1]
        {
            "Attack"
        };
        animState6.Looping = true;
        animState6.Speed.Set(1.61999989f, 1.98f);
        animState6.Enter = delegate
        {
            m_stateMachine.Skeleton.FlipX = false;
            AudioController.Instance.QueueEvent(new AudioEvent(m_audioEventAttack, AUDIOEVENTACTION.Play));
        };
        animState6.AnimComplete = AttackComplete;
        animState6.AnimEvent    = AttackEvent;
        m_stateMachine.Add(animState6);
        AnimState animState7 = new AnimState(6);

        animState7.AnimationNames = new string[1]
        {
            "Captured"
        };
        animState7.Looping = true;
        animState7.Enter   = delegate
        {
            m_stateMachine.Skeleton.FlipX = true;
            AudioController.Instance.QueueEvent(new AudioEvent(m_audioEventCaptured, AUDIOEVENTACTION.Play));
        };
        animState7.Exit = delegate
        {
            AudioController.Instance.QueueEvent(new AudioEvent(m_audioEventCaptured, AUDIOEVENTACTION.Stop));
        };
        m_stateMachine.Add(animState7);
        AnimState animState8 = new AnimState(8);

        animState8.AnimationNames = new string[4]
        {
            "Level0",
            "Level1",
            "Level2",
            "Level3"
        };
        animState8.Looping = true;
        animState8.Enter   = delegate
        {
            m_stateMachine.Skeleton.FlipX = true;
        };
        m_stateMachine.Add(animState8);
        m_stateMachine.NextState = (int)defaultState;
        PlayerData.Instance.MainChunk.Subscribe(delegate
        {
            m_blockFinder.Clear();
        }).AddTo(this);
        (from pair in Singleton <CameraMoveRunner> .Instance.IsCameraMoving.Pairwise()
         select pair.Previous&& !pair.Current into cameraStopped
         where cameraStopped
         select cameraStopped into _
         where m_stateMachine.CurrentState != 6
         select _).Subscribe(delegate
        {
            m_stateMachine.NextState = 0;
        }).AddTo(this);
        Singleton <ChunkRunner> .Instance.BlocksClearTriggered.Subscribe(delegate
        {
            m_stateMachine.NextState = 3;
        }).AddTo(this);

        (from win in Singleton <BossBattleRunner> .Instance.BossBattleResult
         where win
         select win).Subscribe(delegate
        {
            m_stateMachine.NextState = 2;
        }).AddTo(this);
        (from _ in Singleton <ChunkRunner> .Instance.ChapterCompleted
         where m_stateMachine.CurrentState != 6
         select _).Subscribe(delegate
        {
            m_stateMachine.NextState = 0;
        }).AddTo(this);
        (from seq in Singleton <WorldRunner> .Instance.MapSequence.Pairwise()
         where !seq.Current && seq.Previous
         select seq).DelayFrame(1).Subscribe(delegate
        {
            m_stateMachine.NextState = 0;
        }).AddTo(this);
        Singleton <HeroTeamRunner> .Instance.GetOrCreateHeroRunner(m_heroIndex).Tier.Subscribe(delegate(int tier)
        {
            m_stateMachine.PlayOverrideAnimOrdered(8, Mathf.Max(Mathf.Min(tier - 1, 3), 0));
        }).AddTo(this);

        (from tier in Singleton <HeroTeamRunner> .Instance.GetOrCreateHeroRunner(m_heroIndex).Tier
         select Mathf.Max(Mathf.Min(tier, 4), 1)).Subscribe(delegate(int evoLvl)
        {
            switch (evoLvl)
            {
            case 1:
                Speed = 15f;
                break;

            case 2:
                Speed = 30f;
                break;

            case 3:
                Speed = 50f;
                break;

            case 4:
                Speed = 80f;
                break;
            }
        }).AddTo(this);
    }
    public void createAnimation(object state, string _path, float _timeFrame, bool looping,
        bool _isSpecificLoop = false, int[] _specificLoopIndex = null)
    {
        currentState = state;
        isLoop = looping;
        isForced = false;
        special.reset();

        if (listData.ContainsKey(state))
        {
            AnimationStateMachine stateMachine = listData[state];
            frames = stateMachine.Sprites;

            timeFrame = _timeFrame;
            frameLength = stateMachine.Sprites.Length;
            keyStart = currentKeyFrame = 0;
            keyEnd = frames.Length - 1;
            if (frameLength > 1)
            {
                render.sprite = frames[currentKeyFrame];
                isEnable = true;
            }
            else if (frameLength == 1)
            {
                render.sprite = frames[currentKeyFrame];
                isEnable = false;
            }

            if (stateMachine.isSpecificLoop)
            {
                special.set(true, stateMachine.SpecificLoopIndex);
            }
        }
        else
        {
            Resources.UnloadUnusedAssets();
            // frames = Resources.LoadAll<Sprite>(_path);
            Sprite[] temps = Resources.LoadAll<Sprite>(_path);
            frameLength = temps.Length;
            frames = new Sprite[frameLength];
            int index = 0, lenArr = 0;

            for (int i = 0; i < frameLength; i++)
            {
                lenArr = temps[i].name.ToString().Split('_').Length;
                if (lenArr == 1)
                {
                    lenArr = temps[i].name.ToString().Split('-').Length;
                    index = int.Parse((temps[i].name.ToString().Split('-')[lenArr - 1]).ToString());
                    frames[index - 1] = temps[i];
                }
                else
                {
                    index = int.Parse((temps[i].name.ToString().Split('_')[lenArr - 1]).ToString());
                    frames[index - 1] = temps[i];
                }

            }
            timeFrame = _timeFrame;
            keyStart = currentKeyFrame = 0;
            keyEnd = frameLength - 1;

            if (frameLength > 1)
            {
                render.sprite = frames[currentKeyFrame];
                listData.Add(state, new AnimationStateMachine(_timeFrame, frames, _isSpecificLoop));
                isEnable = true;
            }
            else if (frameLength == 1)
            {
                render.sprite = frames[currentKeyFrame];
                listData.Add(state, new AnimationStateMachine(_timeFrame, frames, _isSpecificLoop));
                isEnable = false;
            }

            if (_isSpecificLoop)
            {
                listData[state].SpecificLoopIndex = _specificLoopIndex;
                special.set(true, _specificLoopIndex);
            }
        }

        checkEventFrame();
    }