2012-07-31 108 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