title: Animate opacity over time in XNA
body: <p>I would like to animate the opacity value of a text string containing the name of the level in and out with a delay in the middle.</p>
  
  <p>So the sequence of events would be like:</p>
  
  <ol>
  <li>Start transparent</li>
  <li>Fade in to solid white over a second of game time</li>
  <li>Wait a second</li>
  <li>Fade out to transparent again over a second.</li>
  </ol>
  
  <p>The code I have written to animate the alpha value isn't working. Plus, it's pretty ugly and I'm sure there's a better way to do it using the XNA framework.</p>
  
  <p>I've been unable to find any advice elsewhere about doing this. Surely animating values like this isn't that uncommon. How can I do it?</p>
  
  <p><strong>Here's my current code as requested (yes it's horrible).</strong></p>
  
  <pre><code>private int fadeStringDirection = +1;
  private int fadeStringDuration = 1000;
  private float stringAlpha = 0;
  private int stringRef = 0;
  private int stringPhase = 1;
  
  ...
  
  if (!pause)
  {
      totalMillisecondsElapsed += gameTime.ElapsedGameTime.Milliseconds;
      if (fadestringDirection != 0)
      {
          stringAlpha = ((float)(totalMillisecondsElapsed - stringRef) / (float)(fadeStringDuration*stringPhase)) * fadeStringDirection;
          stringAlpha = MathHelper.Clamp(stringAlpha, 0, 1);
          if (topAlpha / 2 + 0.5 == fadeStringDirection)
          {
              fadeStringDirection = 0;
              stringRef = totalMillisecondsElapsed;
              stringPhase++;
          }
      }
      else
      {
          stringRef += gameTime.ElapsedGameTime.Milliseconds;
          if (stringRef &gt;= fadeStringDuration * stringPhase)
          {
              stringPhase++;
              fadeStringDirection = -1;
              stringRef = totalMillisecondsElapsed;
          }
      }
  }
  </code></pre>