我正在制作一款小游戏,而且我在使用某些动画时遇到了麻烦。 我希望怪物每3秒钟放一些像素,所以我添加了一个有效的条件。但问题是改变怪物位置的函数,被调用的时间超过一次,因为当条件为真时,计时器仍然在滴答作响。
这是计时器:
gameTimer = new System.Timers.Timer();
gameTimer.Elapsed += gameTick;
gameTimer.Interval = 10000/ 60;
gameTimer.Enabled = true;
方法gameTick
:
private void gameTick(object sender, System.Timers.ElapsedEventArgs e)
{
theGame.Update(e.SignalTime.Second);
this.Invalidate();
}
我每隔3秒在gameTick方法中调用的Update方法:
public void Update(int secondsPassed)
{
if(secondsPassed % 3 == 0)
monsters.Update();
}
如何确保方法Update
每3秒仅调用一次?
就像它达到3秒时一样,门打开再次调用更新方法,直到条件变为假。
我不确定我可以添加什么来阻止它再运行一次。
答案 0 :(得分:1)
根据您的需要,您可能希望使用DateTime.Now
捕获上次更新的当前时间,添加3秒并仅在通过时调用Update
:
DateTime nextUpdateTime = DateTime.UtcNow;
private void gameTick(object sender, System.Timers.ElapsedEventArgs e)
{
if (DateTime.UtcNow > nextUpdateTime)
{
nextUpdateTime = DateTime.UtcNow.AddSeconds(3);
theGame.Update(...);
}
....
请注意,如果您计划调试代码,则应避免直接调用DateTime.Now
,并确定在等待断点时如何移动时间。查看http://xboxforums.create.msdn.com/forums/p/53189/322422.aspx有关游戏时间的讨论(XNA论坛)。
答案 1 :(得分:0)
您应该在执行gameTick
时暂停计时器:
private void gameTick(object sender, System.Timers.ElapsedEventArgs e)
{
gameTimer.Enabled = false;
theGame.Update(e.SignalTime.Second);
this.Invalidate();
gameTimer.Enabled = true;
}