Advertisement
kyeahy

XNA TimeAction class

Apr 6th, 2012
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.24 KB | None | 0 0
  1. using System;
  2. using Microsoft.Xna.Framework;
  3.  
  4. namespace BaseXNAGameLibrary.Utils
  5. {
  6.     /// <summary>
  7.     /// Performs an action over a specified amount of time.
  8.     /// The action is an optional Action delegate,
  9.     /// if not set this class simply serves as a mechanism of notifying another class when a certain amount of time has passed.
  10.     ///
  11.     /// Author: Nick Vanheer, immersivenick.wordpress.com
  12.     /// Feel free to extend and let me know if you've made it more powerful!
  13.     /// </summary>
  14.     public class TimeAction
  15.     {
  16.         TimeSpan time = TimeSpan.FromSeconds(1);
  17.         TimeSpan timeSoFar = TimeSpan.Zero;
  18.  
  19.         bool isLoop = false;
  20.  
  21.         public float LerpAmount { get; private set; } /* value between 0 and 1 indicating the current progress (0 = start, 1 = end)  */
  22.  
  23.         /// <summary>
  24.         /// Instantiates a new TimeAction object
  25.         /// </summary>
  26.         /// <param name="time">The time after which something needs to happen</param>
  27.         /// <param name="loop">Repeats the action over the specified time interval</param>
  28.         public TimeAction(TimeSpan time, bool loop = false)
  29.         {
  30.             this.time = time;
  31.             this.isLoop = loop;
  32.         }
  33.  
  34.         /// <summary>
  35.         /// Updates the TimeAction class and executes an optional action after the time interval has been met
  36.         /// </summary>
  37.         /// <param name="gt">The current GameTime</param>
  38.         /// <param name="a">An Action delegate to perform after the specified time has been elapsed (optional)</param>
  39.         /// <returns></returns>
  40.         public bool Update(GameTime gt, Action a = null)
  41.         {
  42.             if (timeSoFar < time)
  43.             {
  44.                 timeSoFar += gt.ElapsedGameTime;
  45.  
  46.                 if (timeSoFar >= time)
  47.                 {
  48.                     if(a != null)
  49.                         a();
  50.  
  51.                     if (isLoop)
  52.                         timeSoFar = new TimeSpan(0, 0, 0);
  53.                     else
  54.                         timeSoFar = time;
  55.  
  56.                     return true;
  57.  
  58.                 }
  59.  
  60.                 LerpAmount = (float)timeSoFar.Ticks / time.Ticks;
  61.  
  62.                 return false;
  63.             }
  64.  
  65.             return false;
  66.         }
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement