2011-04-26 91 views
2

我想動畫中包含延遲的文本字符串的不透明度值,包含級別的名稱。在XNA中動畫不透明度隨着時間的推移

所以事件的順序是這樣的:

  1. 開始透明
  2. 淡入白色固體在遊戲時間的第二
  3. 等待第二個
  4. 淡出透明一遍又一遍一秒。

我編寫的用於爲alpha值設置動畫的代碼不起作用。另外,這非常難看,我確信有更好的方法來使用XNA框架來完成它。

我一直無法找到任何其他建議這樣做。這樣的動畫價值觀並不罕見。我該怎麼做?

這是我的當前代碼(是的,這太可怕了)。

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 >= fadeStringDuration * stringPhase) 
     { 
      stringPhase++; 
      fadeStringDirection = -1; 
      stringRef = totalMillisecondsElapsed; 
     } 
    } 
} 
+0

發佈簡化版本的渲染代碼會有幫助。 – asawyer 2011-04-26 20:20:44

+1

這不是_that_壞。 ;) – 2011-04-26 20:44:30

+0

+1 @Jeff Mercado。只要將它隱藏在AbstractInterpolator/AbstractBouncer/whatever ...類中,並在實際使用它時發現它整潔! – jv42 2011-04-27 08:46:15

回答

2

這是我現在的解決方案。比我之前(以及它自己的班級)更好。

/// <summary> 
/// Animation helper class. 
/// </summary> 
public class Animation 
{ 
    List<Keyframe> keyframes = new List<Keyframe>(); 

    int timeline; 

    int lastFrame = 0; 

    bool run = false; 

    int currentIndex; 

    /// <summary> 
    /// Construct new animation helper. 
    /// </summary> 
    public Animation() 
    { 
    } 

    public void AddKeyframe(int time, float value) 
    { 
     Keyframe k = new Keyframe(); 
     k.time = time; 
     k.value = value; 
     keyframes.Add(k); 
     keyframes.Sort(delegate(Keyframe a, Keyframe b) { return a.time.CompareTo(b.time); }); 
     lastFrame = (time > lastFrame) ? time : lastFrame; 
    } 

    public void Start() 
    { 
     timeline = 0; 
     currentIndex = 0; 
     run = true; 
    } 

    public void Update(GameTime gameTime, ref float value) 
    { 
     if (run) 
     { 
      timeline += gameTime.ElapsedGameTime.Milliseconds; 
      value = MathHelper.SmoothStep(keyframes[currentIndex].value, keyframes[currentIndex + 1].value, (float)timeline/(float)keyframes[currentIndex + 1].time); 
      if (timeline >= keyframes[currentIndex + 1].time && currentIndex != keyframes.Count) { currentIndex++; } 
      if (timeline >= lastFrame) { run = false; } 
     } 
    } 

    public struct Keyframe 
    { 
     public int time; 
     public float value; 
    } 
} 
相關問題