我正在做一个小游戏,我在一些动画上遇到了麻烦。我希望怪物每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方法中调用的更新方法:
public void Update(int secondsPassed)
{
if(secondsPassed % 3 == 0)
monsters.Update();
}如何确保方法Update每3秒只被调用一次?这就像当它到达3秒时,打开门再次调用update方法,直到条件变为false。
我不知道我能在逻辑中添加什么来阻止它再次运行。
发布于 2014-09-02 19:44:00
根据您的需要,您可能希望最后用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论坛)。
发布于 2014-09-02 19:46:01
在执行gameTick时,您应该挂起计时器:
private void gameTick(object sender, System.Timers.ElapsedEventArgs e)
{
gameTimer.Enabled = false;
theGame.Update(e.SignalTime.Second);
this.Invalidate();
gameTimer.Enabled = true;
}https://stackoverflow.com/questions/25630863
复制相似问题