2012-07-31 107 views
2

我需要在我的OpenGL遊戲中將我的精靈移動到每像素路徑(List<Point>軌道)像素,所以我需要實現一種控制時間的方法。我讀了不同的方法:使用OnRenderUpdate(但我不能做任何事情比1/fps更快),使用不同的線程來控制時間或使用StopWatch(而不是Timer)。我想用最後一個:定時移動精靈

private void Sprite_Move(Sprite sprite, List<Point> path) { 
    track.Clear(); 
    for (int i = 1; i < path.Count; i++) { 
    //memorize all track pixel, so I can update pixel per pixel my sprite position 
    Bresenham2(path[i-1], path[i]); 
    } 
    //moving flag 
    sprite.moving = true; 
    //start my StopWatch 
    timer.Start(); 
    Loop(timer, sprite); 

} 

private void Loop(Stopwatch timer, Sprite sprite) { 
    int i = 1; 
    while (timer.IsRunning) { 
    //moving each 0.03s? 
    if ((sprite.moving) & (timer.Elapsed.Milliseconds >= 30)) { 
     if (i < track.Count) { 
     //change sprite position to the i-th track pixel 
     Sprite_Position(skinny, track[i]); 
     i++; 
     timer = StopWatch.StartNew(); 
     Console.WriteLine("Tick"); 
     } 
     //if I'm on the end of the track I can exit 
     else timer.Stop(); 
    } 
    } 
} 

我看不到我的精靈正在移動。一切都被阻塞,直到最後一次迭代,然後我看到我的精靈在軌道的最後一個像素......瞬間!

+0

「OnRenderUpdate」是你應該使用的。 – asawyer 2012-07-31 13:00:33

+0

如果我強迫我的遊戲以30 fps運行,我無法做出比1/fps更快的移動。 – 2012-07-31 13:06:46

+0

這沒有任何意義。 – asawyer 2012-07-31 13:07:42

回答

2

您可以使用某種全局時間值而不是依靠計時器來正確打勾,這取決於您的框架或StopWatch,並查看其耗用的時間。

舉例來說,如果你在你的動畫N個步驟,和動畫完全應該採取T秒跑,你會發現通過

int frame = (int)((CurrentTimeInSeconds/(float)T) * N) 

爲動畫的正確步驟(不要照顧溢出,即如果frame> = N,則不再做任何事情。)

0

那麼,StopWatch.Reset()也停止計時器。 見here。 因此,在第一次迭代之後,您的timer.IsRunning將爲false。

相反,您可以在循環中使用timer.StartNew()

關於動畫時間: 我認爲秒錶是可以的。 使用秒錶或單獨的線程可以讓您獨立於渲染速度。 雖然這不應該是一個問題,而你堅持2D動畫的精靈。

從我的舊項目:

m_LastPoll.Stop(); 
    System.Diagnostics.Debug.Print("{0}:\t{1}", this.VendorID, m_LastPoll.ElapsedMilliseconds); 
    m_LastPoll.Reset(); 
    m_LastPoll.Start(); 

這肯定工作。

+0

timer = StopWatch.StartNew();它不工作.. – 2012-07-31 13:26:40

+0

確定它的工作原理,但我看不到我的精靈正在移動。只是在最後的位置,當我的循環完成工作... – 2012-07-31 13:37:10

+0

嗡嗡...奇怪。 StartNew應該可以工作。你也可以使用「timer.Start();」重置後。 – 2012-07-31 13:45:39