TransitionGameComponentAnimation.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //-----------------------------------------------------------------------------
  2. // TransitionGameComponentAnimation.cs
  3. //
  4. // Microsoft XNA Community Game Platform
  5. // Copyright (C) Microsoft Corporation. All rights reserved.
  6. //-----------------------------------------------------------------------------
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Text;
  10. using Microsoft.Xna.Framework;
  11. namespace CardsFramework
  12. {
  13. /// <summary>
  14. /// An animation which moves a component from one point to the other.
  15. /// </summary>
  16. public class TransitionGameComponentAnimation : AnimatedGameComponentAnimation
  17. {
  18. Vector2 sourcePosition;
  19. Vector2 positionDelta;
  20. float percent = 0;
  21. Vector2 destinationPosition;
  22. /// <summary>
  23. /// Initializes a new instance of the class.
  24. /// </summary>
  25. /// <param name="sourcePosition">The source position.</param>
  26. /// <param name="destinationPosition">The destination position.</param>
  27. public TransitionGameComponentAnimation(Vector2 sourcePosition,
  28. Vector2 destinationPosition)
  29. {
  30. this.destinationPosition = destinationPosition;
  31. this.sourcePosition = sourcePosition;
  32. positionDelta = destinationPosition - sourcePosition;
  33. }
  34. /// <summary>
  35. /// Runs the transition animation.
  36. /// </summary>
  37. /// <param name="gameTime">Game time information.</param>
  38. public override void Run(GameTime gameTime)
  39. {
  40. if (IsStarted())
  41. {
  42. // Calculate the animation's completion percentage.
  43. percent += (float)(gameTime.ElapsedGameTime.TotalSeconds / Duration.TotalSeconds);
  44. percent = MathHelper.Clamp(percent, 0f, 1f);
  45. // Apply cubic ease-out for smooth sliding
  46. float easedPercent = EaseOutCubic(percent);
  47. Component.CurrentPosition = sourcePosition + positionDelta * easedPercent;
  48. if (IsDone())
  49. {
  50. Component.CurrentPosition = destinationPosition;
  51. }
  52. }
  53. }
  54. /// <summary>
  55. /// Cubic ease-out function for smooth animation.
  56. /// </summary>
  57. private float EaseOutCubic(float t)
  58. {
  59. return 1f - (float)Math.Pow(1f - t, 2);
  60. }
  61. }
  62. }