示例#1
0
 public bool TryGetSheet(AvatarAnimation animation, out AnimationSheet sheet)
 {
     sheet = animation == AvatarAnimation.Unknown
         ? default
         : animations[(int)animation];
     return(sheet);
 }
示例#2
0
        /// <summary>
        /// Load your graphics content.
        /// </summary>
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            font        = Content.Load <SpriteFont>("Font");

            // Create random avatar description and load the renderer and animation
            avatarDescription = AvatarDescription.CreateRandom();
            avatarRenderer    = new AvatarRenderer(avatarDescription);

            // Load 4 of the preset animations
            avatarAnimations    = new AvatarAnimation[4];
            avatarAnimations[0] = new AvatarAnimation(AvatarAnimationPreset.Stand0);
            avatarAnimations[1] = new AvatarAnimation(AvatarAnimationPreset.Celebrate);
            avatarAnimations[2] = new AvatarAnimation(AvatarAnimationPreset.Clap);
            avatarAnimations[3] = new AvatarAnimation(AvatarAnimationPreset.Wave);

            // Create new blended animation
            blendedAnimation = new AvatarBlendedAnimation(avatarAnimations[0]);

            noBlendingAnimation = avatarAnimations[0];

            // Initialize the rendering matrices
            world      = Matrix.CreateRotationY(MathHelper.Pi);
            projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
                                                             GraphicsDevice.Viewport.AspectRatio,
                                                             .01f, 200.0f);
        }
示例#3
0
 public Avatar()
 {
     // We pick a random animation and description for each avatar we create
     Animation   = new AvatarAnimation((AvatarAnimationPreset)random.Next(30));
     Description = AvatarDescription.CreateRandom();
     Renderer    = new AvatarRenderer(Description, false);
 }
示例#4
0
 public void Awake()
 {
     // Create modules.
     avatarComponent = new AvatarComponent(this); // Avatar component module.
     avatarAnimation = new AvatarAnimation(this);
     avatarFx        = new AvatarFx(this);        // Avatar effect module.
 }
        /// <summary>
        /// Load your graphics content.
        /// </summary>
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            font        = Content.Load <SpriteFont>("Font");

            // Create random avatar description and load the renderer and animation
            avatarDescription = AvatarDescription.CreateRandom();
            avatarRenderer    = new AvatarRenderer(avatarDescription);

            // Load the preset animations
            waveAnimation      = new AvatarAnimation(AvatarAnimationPreset.Wave);
            celebrateAnimation = new AvatarAnimation(AvatarAnimationPreset.Celebrate);

            // Find the bone index values for the right arm and its children
            rightArmBones = FindInfluencedBones(AvatarBone.ShoulderRight,
                                                avatarRenderer.ParentBones);

            for (int i = 0; i < AvatarRenderer.BoneCount; ++i)
            {
                finalBoneTransforms.Add(Matrix.Identity);
            }

            // Initialize the rendering matrices
            world      = Matrix.CreateRotationY(MathHelper.Pi);
            projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
                                                             GraphicsDevice.Viewport.AspectRatio,
                                                             .01f, 200.0f);
        }
示例#6
0
    private void MockMovement()
    {
        var list = new List<Dictionary<string, float[]>>();
        var initial = new Dictionary<string, float[]>();
        var final = new Dictionary<string, float[]>();
        var final2 = new Dictionary<string, float[]>();
        var final3 = new Dictionary<string, float[]>();
        initial.Add("leftArm",      new float[] { 0, 80, -105, 1 });
        initial.Add("leftForearm",  new float[] { 75, 0, 0, 1 });
        final.Add("leftHand",       new float[] { 0, 20, 0, 0.5f });
        final2.Add("leftHand",      new float[] { 0, -40, 0, 1 });
        final3.Add("leftHand",      new float[] { 0, 20, 0, 0.5f });
        initial.Add("rightArm",     new float[] { 0, 80, -105, 1 });
        initial.Add("rightForearm", new float[] { 75, 0, 0, 1 });
        final.Add("rightHand",      new float[] { 0, 20, 0, 0.5f });
        final2.Add("rightHand",     new float[] { 0, -40, 0, 1 });
        final3.Add("rightHand",     new float[] { 0, 20, 0, 0.5f });
        list.Add(initial);
        list.Add(final);
        list.Add(final2);
        list.Add(final3);
        avatarAnimation = new AvatarAnimation(list, 0.1f, "leftArmSide", true);

        SetCamera("chest");

        JSON json = new JSON();
        json["avatarAnimation"] = (JSON)avatarAnimation;

        Debug.Log(json.serialized);

        RestartAnimation();

        state = State.ANIMATING;
    }
示例#7
0
        /// <summary>
        /// Load your graphics content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create random avatar description and load the renderer and animation
            avatarDescription = AvatarDescription.CreateRandom();
            avatarRenderer    = new AvatarRenderer(avatarDescription);

            // Load 4 of the preset animations
            avatarAnimations[0] = new AvatarAnimation(AvatarAnimationPreset.Stand0);
            avatarAnimations[1] = new AvatarAnimation(AvatarAnimationPreset.Celebrate);
            avatarAnimations[2] = new AvatarAnimation(AvatarAnimationPreset.Clap);
            avatarAnimations[3] = new AvatarAnimation(AvatarAnimationPreset.Stand5);

            // Current animation to play and update
            currentAvatarAnimation = avatarAnimations[0];

            // Load the baseball bat model
            baseballBat = Content.Load <Model>("baseballbat");

            // Initialize the rendering matrices
            world      = Matrix.CreateRotationY(MathHelper.Pi);
            projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
                                                             GraphicsDevice.Viewport.AspectRatio,
                                                             .01f, 200.0f);

            // Initialize the list of bones in world space
            bonesWorldSpace = new List <Matrix>(AvatarRenderer.BoneCount);
            for (int i = 0; i < AvatarRenderer.BoneCount; i++)
            {
                bonesWorldSpace.Add(Matrix.Identity);
            }
        }
示例#8
0
 private void ProcessCall(GuideCall call)
 {
     switch (call.Key) {
         case State.ANIMATING:
             if (call.Value != null) {
                 avatarAnimation = call.Value;
                 SetCamera(avatarAnimation.GetCameraPosition());
                 RestartAnimation();
                 state = State.ANIMATING;
             }
             else if (avatarAnimation == null) {
                 Debug.LogError("Attempting to resume a null animation!");
             }
             else if (timer > 0) {
                 state = State.WAITING;
             }
             else {
                 state = State.ANIMATING;
             }
             break;
         case State.PAUSED:
             state = State.PAUSED;
             break;
         case State.IDLE:
             state = State.IDLE;
             foreach (KeyValuePair<string, Member> entry in memberTable) {
                 entry.Value.Reset();
             }
             avatarAnimation = null;
             break;
         default:
             Debug.Log("Unexpected call type fetched from GuideDriver.");
             break;
     }
 }
示例#9
0
        /// <summary>
        /// Updates a list of matrices to represent the location of the
        /// avatar bones in world space with the avatar animation applied.
        /// </summary>
        private static void BonesToWorldSpace(AvatarRenderer renderer, AvatarAnimation animation,
                                              List <Matrix> boneToUpdate)
        {
            // Bind pose of the avatar.
            // These positions are in local space, and are relative to the parent bone.
            IList <Matrix> bindPose = renderer.BindPose;
            // The current animation pose.
            // These positions are in local space, and are relative to the parent bone.
            IList <Matrix> animationPose = animation.BoneTransforms;
            // List of parent bones for each bone in the hierarchy
            IList <int> parentIndex = renderer.ParentBones;

            // Loop all of the bones.
            // Since the bone hierarchy is sorted by depth
            // we will transform the parent before any child.
            for (int i = 0; i < AvatarRenderer.BoneCount; i++)
            {
                // Find the transform of this bones parent.
                // If this is the first bone use the world matrix used on the avatar
                Matrix parentMatrix = (parentIndex[i] != -1)
                                       ? boneToUpdate[parentIndex[i]]
                                       : renderer.World;
                // Calculate this bones world space position
                boneToUpdate[i] = Matrix.Multiply(Matrix.Multiply(animationPose[i],
                                                                  bindPose[i]),
                                                  parentMatrix);
            }
        }
示例#10
0
 protected override void SendAnimations(AvatarAnimation m)
 {
     foreach (AgentCircuit c in Circuits.Values)
     {
         c.Scene.SendAgentAnimToAllAgents(m);
     }
 }
示例#11
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="startingAnimation">The first animation to play</param>
        public AvatarBlendedAnimation(AvatarAnimation startingAnimation)
        {
            // Set the first animation
            currentAnimation = startingAnimation;

            // Create collection we will use for blended transfroms
            boneTransforms = new ReadOnlyCollection <Matrix>(avatarBones);
        }
示例#12
0
        public AvatarAnimationController(AvatarRenderer renderer, AvatarAnimationPreset preset)
        {
            if (renderer == null)
            {
                throw new ArgumentNullException("renderer");
            }

            Renderer        = renderer;
            Loop            = true;
            avatarAnimation = new AvatarAnimation(preset);
        }
        public WrappedAvatarSkeletonAnimation(AvatarAnimation avatarAnimation)
        {
            if (avatarAnimation == null)
            {
                throw new ArgumentNullException("avatarAnimation");
            }

            _avatarAnimation = avatarAnimation;

            // Per default, this animation animates the SkeletonPose property of the AvatarPose class.
            TargetProperty = "SkeletonPose";
        }
示例#14
0
        /// <summary>
        /// Handles input for quitting the game.
        /// </summary>
        void HandleInput()
        {
            lastGamePadState    = currentGamePadState;
            currentGamePadState = GamePad.GetState(PlayerIndex.One);

            // Check for exit.
            if (currentGamePadState.Buttons.Back == ButtonState.Pressed)
            {
                Exit();
            }

            // Check to see if we need to change blending bool
            if (currentGamePadState.Buttons.LeftShoulder == ButtonState.Pressed &&
                lastGamePadState.Buttons.LeftShoulder != ButtonState.Pressed)
            {
                useAnimationBlending = !useAnimationBlending;
            }

            // Check to see if we should load another random avatar
            if (currentGamePadState.Buttons.RightShoulder == ButtonState.Pressed &&
                lastGamePadState.Buttons.RightShoulder != ButtonState.Pressed)
            {
                avatarDescription = AvatarDescription.CreateRandom();
                avatarRenderer    = new AvatarRenderer(avatarDescription);
            }

            // Check to see if we need to play another animation
            if (currentGamePadState.Buttons.A == ButtonState.Pressed &&
                lastGamePadState.Buttons.A != ButtonState.Pressed)
            {
                blendedAnimation.Play(avatarAnimations[1]);
                noBlendingAnimation = avatarAnimations[1];
            }
            else if (currentGamePadState.Buttons.B == ButtonState.Pressed &&
                     lastGamePadState.Buttons.B != ButtonState.Pressed)
            {
                blendedAnimation.Play(avatarAnimations[2]);
                noBlendingAnimation = avatarAnimations[2];
            }
            else if (currentGamePadState.Buttons.X == ButtonState.Pressed &&
                     lastGamePadState.Buttons.X != ButtonState.Pressed)
            {
                blendedAnimation.Play(avatarAnimations[0]);
                noBlendingAnimation = avatarAnimations[0];
            }
            else if (currentGamePadState.Buttons.Y == ButtonState.Pressed &&
                     lastGamePadState.Buttons.Y != ButtonState.Pressed)
            {
                blendedAnimation.Play(avatarAnimations[3]);
                noBlendingAnimation = avatarAnimations[3];
            }
        }
示例#15
0
        /// <summary>
        /// Load all graphical content.
        /// </summary>
        protected override void LoadContent()
        {
            // Load custom animations
            CustomAvatarAnimationData animationData;

            // We will use 8 different animations
            animations = new IAvatarAnimation[9];

            // Load the idle animations
            for (int i = 0; i < 4; i++)
            {
                animations[i] = new AvatarAnimation(
                    (AvatarAnimationPreset)((int)AvatarAnimationPreset.Stand0 + i));
            }


            // Load the walk animation
            animationData = Content.Load <CustomAvatarAnimationData>("Walk");
            animations[4] = new CustomAvatarAnimationPlayer(animationData.Name, animationData.Length,
                                                            animationData.Keyframes, animationData.ExpressionKeyframes);

            // Load the jump animation
            animationData = Content.Load <CustomAvatarAnimationData>("Jump");
            animations[5] = new CustomAvatarAnimationPlayer(animationData.Name, animationData.Length,
                                                            animationData.Keyframes, animationData.ExpressionKeyframes);

            // Load the kick animation
            animationData = Content.Load <CustomAvatarAnimationData>("Kick");
            animations[6] = new CustomAvatarAnimationPlayer(animationData.Name, animationData.Length,
                                                            animationData.Keyframes, animationData.ExpressionKeyframes);

            // Load the punch animation
            animationData = Content.Load <CustomAvatarAnimationData>("Punch");
            animations[7] = new CustomAvatarAnimationPlayer(animationData.Name, animationData.Length,
                                                            animationData.Keyframes, animationData.ExpressionKeyframes);

            // Load the faint animation
            animationData = Content.Load <CustomAvatarAnimationData>("Faint");
            animations[8] = new CustomAvatarAnimationPlayer(animationData.Name, animationData.Length,
                                                            animationData.Keyframes, animationData.ExpressionKeyframes);

            // Load the model for the ground
            groundModel = Content.Load <Model>("ground");

            // Select a random idle animation to start
            PlayRandomIdle();

            // Create the projection to use
            projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f),
                                                             GraphicsDevice.Viewport.AspectRatio, .01f, 200.0f);
            world = Matrix.Identity;
        }
示例#16
0
 public void Reset()
 {
     if (_isInitialized)
     {
         if (_animator != null)
         {
             SetAnimation(AvatarAnimation.idle);
         }
         _currentAnimation = AvatarAnimation.idle;
         _fadeOutTimer     = null;
         SetMaterialColor(new Color(1.0f, 1.0f, 1.0f, 1.0f));
     }
 }
示例#17
0
        public ITimeline WrapAnimation(AvatarAnimationPreset preset)
        {
            // Return a timeline group that contains one animation for the Expression and one
            // animation for the SkeletonPose.
            var avatarAnimation     = new AvatarAnimation(_currentAvatarAnimationPreset);
            var expressionAnimation = new WrappedAvatarExpressionAnimation(avatarAnimation);
            var skeletonAnimation   = new WrappedAvatarSkeletonAnimation(avatarAnimation);

            return(new TimelineGroup
            {
                expressionAnimation,
                skeletonAnimation,
            });
        }
示例#18
0
 public void SendAgentAnimToAllAgents(AvatarAnimation areq)
 {
     foreach (IAgent a in Agents)
     {
         if (a.Owner.ID == areq.Sender)
         {
             a.SendMessageIfRootAgent(areq, ID);
         }
         else
         {
             a.SendMessageAlways(areq, ID);
         }
     }
 }
示例#19
0
        /// <summary>
        /// Plays a new animation and blends from the current animation.
        /// </summary>
        /// <param name="nextAnimation">Next animation to play</param>
        public void Play(AvatarAnimation nextAnimation)
        {
            // Check to make sure we are not already playing the animation passed in
            if (currentAnimation == nextAnimation)
            {
                return;
            }

            // Set the next animation
            targetAnimation = nextAnimation;

            // Reset the animation to the start
            targetAnimation.CurrentPosition = TimeSpan.Zero;

            // Reset the blend current time to zero
            blendCurrentTime = TimeSpan.Zero;
        }
        public AvatarAnimation GetAvatarAnimation()
        {
            var m = new AvatarAnimation
            {
                Sender = m_AgentID
            };

            lock (m_Lock)
            {
                foreach (var ai in m_ActiveAnimations)
                {
                    m.AnimationList.Add(new AvatarAnimation.AnimationData(ai.AnimID, ai.AnimSeq, ai.SourceID));
                }
            }

            return(m);
        }
示例#21
0
        /// <summary>
        /// Handles input for quitting the game.
        /// </summary>
        void HandleInput()
        {
            lastGamePadState    = currentGamePadState;
            currentGamePadState = GamePad.GetState(PlayerIndex.One);

            // Check for exit.
            if (currentGamePadState.Buttons.Back == ButtonState.Pressed)
            {
                Exit();
            }

            // Check to see if we should load another random avatar
            if (currentGamePadState.Buttons.RightShoulder == ButtonState.Pressed &&
                lastGamePadState.Buttons.RightShoulder != ButtonState.Pressed)
            {
                avatarDescription = AvatarDescription.CreateRandom();
                avatarRenderer    = new AvatarRenderer(avatarDescription);
            }

            // Check to see if we need to play another animation
            if (currentGamePadState.Buttons.A == ButtonState.Pressed &&
                lastGamePadState.Buttons.A != ButtonState.Pressed)
            {
                currentAvatarAnimation = avatarAnimations[1];
                currentAvatarAnimation.CurrentPosition = TimeSpan.Zero;
            }
            else if (currentGamePadState.Buttons.B == ButtonState.Pressed &&
                     lastGamePadState.Buttons.B != ButtonState.Pressed)
            {
                currentAvatarAnimation = avatarAnimations[2];
                currentAvatarAnimation.CurrentPosition = TimeSpan.Zero;
            }
            else if (currentGamePadState.Buttons.X == ButtonState.Pressed &&
                     lastGamePadState.Buttons.X != ButtonState.Pressed)
            {
                currentAvatarAnimation = avatarAnimations[3];
                currentAvatarAnimation.CurrentPosition = TimeSpan.Zero;
            }
            else if (currentGamePadState.Buttons.Y == ButtonState.Pressed &&
                     lastGamePadState.Buttons.Y != ButtonState.Pressed)
            {
                currentAvatarAnimation = avatarAnimations[0];
                currentAvatarAnimation.CurrentPosition = TimeSpan.Zero;
            }
        }
        public CustomAvatarAnimationSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;

            // Add a custom game object which controls the camera.
            _cameraObject = new CameraObject(Services);
            _cameraObject.ResetPose(new Vector3(0, 1, -3), ConstantsF.Pi, 0);
            GameObjectService.Objects.Add(_cameraObject);

            // Create a random avatar.
            _avatarDescription = AvatarDescription.CreateRandom();
            _avatarRenderer    = new AvatarRenderer(_avatarDescription);

            // Wrap the Stand0 AvatarAnimationPreset (see WrappedAnimationSample) to create an
            // infinitely looping stand animation.
            AvatarAnimation standAnimationPreset = new AvatarAnimation(AvatarAnimationPreset.Stand0);
            TimelineGroup   standAnimation       = new TimelineGroup
            {
                new WrappedAvatarExpressionAnimation(standAnimationPreset),
                new WrappedAvatarSkeletonAnimation(standAnimationPreset),
            };

            _standAnimation = new TimelineClip(standAnimation)
            {
                LoopBehavior = LoopBehavior.Cycle, // Cycle the Stand animation...
                Duration     = TimeSpan.MaxValue,  // ...forever.
            };

            // Load animations from content pipeline.
            _faintAnimation = ContentManager.Load <TimelineGroup>("XboxAvatars/Faint");
            _jumpAnimation  = ContentManager.Load <TimelineGroup>("XboxAvatars/Jump");
            _kickAnimation  = ContentManager.Load <TimelineGroup>("XboxAvatars/Kick");
            _punchAnimation = ContentManager.Load <TimelineGroup>("XboxAvatars/Punch");

            // The walk cycle should loop: Put it into a timeline clip and set a
            // loop-behavior.
            TimelineGroup walkAnimation = ContentManager.Load <TimelineGroup>("XboxAvatars/Walk");

            _walkAnimation = new TimelineClip(walkAnimation)
            {
                LoopBehavior = LoopBehavior.Cycle, // Cycle the Walk animation...
                Duration     = TimeSpan.MaxValue,  // ...forever.
            };
        }
		public void Reset()
		{
			if (_isInitialized)
			{
				if (_animator != null)
					SetAnimation(AvatarAnimation.idle);
				_currentAnimation = AvatarAnimation.idle;
				_fadeOutTimer = null;
				SetMaterialColor(Color.white);
			}
		}
        public AdvancedAvatarRagdollSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            SampleFramework.IsMouseVisible = false;

            // This sample uses for a DebugRenderer to draw text and rigid bodies.
            _debugRenderer = new DebugRenderer(GraphicsService, SpriteFont)
            {
                DefaultColor        = Color.Black,
                DefaultTextPosition = new Vector2F(10),
            };

            // Add a custom game object which controls the camera.
            _cameraObject = new CameraObject(Services);
            _cameraObject.ResetPose(new Vector3(0, 1, -3), ConstantsF.Pi, 0);
            GameObjectService.Objects.Add(_cameraObject);

            // Add some objects which allow the user to interact with the rigid bodies.
            _grabObject        = new GrabObject(Services);
            _ballShooterObject = new BallShooterObject(Services)
            {
                Speed = 20
            };
            GameObjectService.Objects.Add(_grabObject);
            GameObjectService.Objects.Add(_ballShooterObject);

            // Add some default force effects.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Create a random avatar.
            _avatarDescription = AvatarDescription.CreateRandom();
            _avatarRenderer    = new AvatarRenderer(_avatarDescription);

            // Use the "Wave" animation preset.
            var avatarAnimation = new AvatarAnimation(AvatarAnimationPreset.Wave);

            _expressionAnimation = new AnimationClip <AvatarExpression>(new WrappedAvatarExpressionAnimation(avatarAnimation))
            {
                LoopBehavior = LoopBehavior.Cycle,
                Duration     = TimeSpan.MaxValue,
            };
            _skeletonAnimation = new AnimationClip <SkeletonPose>(new WrappedAvatarSkeletonAnimation(avatarAnimation))
            {
                LoopBehavior = LoopBehavior.Cycle,
                Duration     = TimeSpan.MaxValue,
            };

            // Add a ground plane in the simulation.
            Simulation.RigidBodies.Add(new RigidBody(new PlaneShape(Vector3.UnitY, 0))
            {
                MotionType = MotionType.Static
            });

            // Distribute a few dynamic spheres and boxes across the landscape.
            SphereShape sphereShape = new SphereShape(0.3f);

            for (int i = 0; i < 10; i++)
            {
                Vector3 position = RandomHelper.Random.NextVector3(-10, 10);
                position.Y = 1;
                Simulation.RigidBodies.Add(new RigidBody(sphereShape)
                {
                    Pose = new Pose(position)
                });
            }

            BoxShape boxShape = new BoxShape(0.6f, 0.6f, 0.6f);

            for (int i = 0; i < 10; i++)
            {
                Vector3 position = RandomHelper.Random.NextVector3(-10, 10);
                position.Y = 1;
                Simulation.RigidBodies.Add(new RigidBody(boxShape)
                {
                    Pose = new Pose(position)
                });
            }
        }
示例#25
0
 protected abstract void SendAnimations(AvatarAnimation m);
 protected override void SendAnimations(AvatarAnimation m)
 {
     CurrentScene?.SendAgentAnimToAllAgents(m);
 }
 public void Play(AvatarAnimation animation, float normalizedTime)
 {
     _animator.Play((int)animation, -1, normalizedTime);
 }
 public void Play(AvatarAnimation animation)
 {
     _animator.Play((int)animation);
 }
示例#29
0
        private void SetAnimation(AvatarAnimation anim)
        {
            if (_animator == null)
            {
                return;
            }

            if (_currentAnimation != anim)
            {
                switch (anim)
                {
                case AvatarAnimation.idle:
                    _animator.SetTrigger("idle");
                    if (_animator.GetBool("walk"))
                    {
                        _animator.SetBool("walk", false);
                    }
                    break;

                case AvatarAnimation.walk:
                    if (_animator.GetBool("idle"))
                    {
                        _animator.SetBool("idle", false);
                    }
                    if (_animator.GetBool("die"))
                    {
                        _animator.SetBool("die", false);
                    }
                    _animator.SetTrigger("walk");
                    break;

                case AvatarAnimation.attack:
                    // this is important
                    // it could be that both parameters are triggered in this frame and in this case the action is more important, so we disable the other parameter
                    if (_animator.GetBool("walk"))
                    {
                        _animator.SetBool("walk", false);
                    }
                    _animator.SetTrigger("attack");
                    break;

                case AvatarAnimation.die:
                    _animator.SetTrigger("die");

                    // set all other triggers to false so Mecanim knows exactly which state to trigger
                    if (_animator.GetBool("walk"))
                    {
                        _animator.SetBool("walk", false);
                    }
                    if (_animator.GetBool("idle"))
                    {
                        _animator.SetBool("idle", false);
                    }
                    if (_animator.GetBool("attack"))
                    {
                        _animator.SetBool("attack", false);
                    }
                    break;

                default:
                    _animator.SetTrigger(anim.ToString());
                    break;
                }

                _currentAnimation = anim;
            }
        }
示例#30
0
        /// <summary>
        /// Updates the animation and blends with the next animation if there is one.
        /// </summary>
        /// <param name="elapsedAnimationTime">Time since the last update</param>
        /// <param name="loop">Should the animation loop</param>
        public void Update(TimeSpan elapsedAnimationTime, bool loop)
        {
            // Update the current animation
            currentAnimation.Update(elapsedAnimationTime, loop);

            // Check to see if we need to blend animations or not
            if (targetAnimation == null)
            {
                // We are not blending so copy the current animations bone transforms
                currentAnimation.BoneTransforms.CopyTo(avatarBones, 0);
            }
            else
            {
                // Update the target animation
                targetAnimation.Update(elapsedAnimationTime, loop);

                ReadOnlyCollection <Matrix> currentBoneTransforms =
                    currentAnimation.BoneTransforms;
                ReadOnlyCollection <Matrix> targetBoneTransforms =
                    targetAnimation.BoneTransforms;

                // Update the current blended time
                blendCurrentTime += elapsedAnimationTime;

                // Calculate blend factor
                float blendFactor = (float)(blendCurrentTime.TotalSeconds /
                                            blendTotalTime.TotalSeconds);


                // Check to see if we are done blending
                if (blendFactor >= 1.0f)
                {
                    // Set the current animtion and remove the target animation
                    currentAnimation = targetAnimation;
                    targetAnimation  = null;
                    blendFactor      = 1.0f;
                }

                // Variables to hold the rotations and translations for the
                // current, target, and blended transforms
                Quaternion currentRotation, targetRotation, finalRotation;
                Vector3    currentTranslation, targetTranslation, finalTranslation;

                // Loop all of the bones in the avatar
                for (int i = 0; i < avatarBones.Length; ++i)
                {
                    // Find the rotation of the current and target bone transforms
                    currentRotation =
                        Quaternion.CreateFromRotationMatrix(currentBoneTransforms[i]);
                    targetRotation =
                        Quaternion.CreateFromRotationMatrix(targetBoneTransforms[i]);

                    // Calculate the blended rotation from the current to the target
                    Quaternion.Slerp(ref currentRotation, ref targetRotation,
                                     blendFactor, out finalRotation);

                    // Find the translation of the current and target bone transforms
                    currentTranslation = currentBoneTransforms[i].Translation;
                    targetTranslation  = targetBoneTransforms[i].Translation;

                    // Calculate the blended translation from the current to the target
                    Vector3.Lerp(ref currentTranslation, ref targetTranslation,
                                 blendFactor, out finalTranslation);

                    // Build the final bone transform
                    avatarBones[i] = Matrix.CreateFromQuaternion(finalRotation) *
                                     Matrix.CreateTranslation(finalTranslation);
                }
            }
        }
		private void SetAnimation(AvatarAnimation anim)
		{
			if (_animator == null)
			{
				return;
			}

			if (_currentAnimation != anim)
			{
				switch (anim)
				{
					case AvatarAnimation.idle:
						_animator.SetTrigger("idle");
						if (_animator.GetBool("walk"))
						{
							_animator.SetBool("walk", false);
						}
						break;
					case AvatarAnimation.walk:
						if (_animator.GetBool("idle"))
						{
							_animator.SetBool("idle", false);
						}
						if (_animator.GetBool("die"))
						{
							_animator.SetBool("die", false);
						}
						_animator.SetTrigger("walk");
						break;
					case AvatarAnimation.attack:
						// this is important
						// it could be that both parameters are triggered in this frame and in this case the action is more important, so we disable the other parameter
						if (_animator.GetBool("walk"))
						{
							_animator.SetBool("walk", false);
						}
						_animator.SetTrigger("attack");
						break;
					case AvatarAnimation.die:
						_animator.SetTrigger("die");

						// set all other triggers to false so Mecanim knows exactly which state to trigger
						if (_animator.GetBool("walk"))
						{
							_animator.SetBool("walk", false);
						}
						if (_animator.GetBool("idle"))
						{
							_animator.SetBool("idle", false);
						}
						if (_animator.GetBool("attack"))
						{
							_animator.SetBool("attack", false);
						}
						break;
					default:
						_animator.SetTrigger(anim.ToString());
						break;
				}

				_currentAnimation = anim;
			}
		}
        private ITimeline BakeAnimation(AvatarAnimation avatarAnimation)
        {
            // Create an AvatarExpression key frame animation that will be applied to the Expression
            // property of an AvatarPose.
            AvatarExpressionKeyFrameAnimation expressionAnimation = new AvatarExpressionKeyFrameAnimation
            {
                TargetProperty = "Expression"
            };

            // Create a SkeletonPose key frame animation that will be applied to the SkeletonPose
            // property of an AvatarPose.
            SkeletonKeyFrameAnimation skeletonKeyFrameAnimation = new SkeletonKeyFrameAnimation
            {
                TargetProperty = "SkeletonPose"
            };

            // In the next loop, we sample the original animation with 30 Hz and store the key frames.
            int numberOfKeyFrames = 0;
            AvatarExpression previousExpression = new AvatarExpression();
            TimeSpan         time   = TimeSpan.Zero;
            TimeSpan         length = avatarAnimation.Length;
            TimeSpan         step   = new TimeSpan(333333); //  1/30 seconds;

            while (true)
            {
                // Advance time in AvatarAnimation.
                avatarAnimation.CurrentPosition = time;

                // Add expression key frame if this is the first key frame or if the key frame is
                // different from the last key frame.
                AvatarExpression expression = avatarAnimation.Expression;
                if (time == TimeSpan.Zero || !expression.Equals(previousExpression))
                {
                    expressionAnimation.KeyFrames.Add(new KeyFrame <AvatarExpression>(time, expression));
                }

                previousExpression = expression;

                // Convert bone transforms to SrtTransforms and add key frames to the SkeletonPose
                // animation.
                for (int i = 0; i < avatarAnimation.BoneTransforms.Count; i++)
                {
                    SrtTransform boneTransform = SrtTransform.FromMatrix(avatarAnimation.BoneTransforms[i]);
                    skeletonKeyFrameAnimation.AddKeyFrame(i, time, boneTransform);
                    numberOfKeyFrames++;
                }

                // Abort if we have arrived at the end time.
                if (time == length)
                {
                    break;
                }

                // Increase time. We check that we do not step over the end time.
                if (time + step > length)
                {
                    time = length;
                }
                else
                {
                    time += step;
                }
            }

            // Compress animation to save memory.
            float numberOfRemovedKeyFrames = skeletonKeyFrameAnimation.Compress(0.1f, 0.1f, 0.001f);

            Debug.WriteLine("Compression removed " + numberOfRemovedKeyFrames * 100 + "% of the key frames.");

            // Finalize the skeleton key frame animation. This optimizes the internal data structures.
            skeletonKeyFrameAnimation.Freeze();

            return(new TimelineGroup
            {
                expressionAnimation,
                skeletonKeyFrameAnimation,
            });
        }