How do I make a “loop” for a game, that runs every (number) of milliseconds?

一曲冷凌霜 提交于 2019-12-13 05:08:46

问题


I've tried to search for this on google and stackoverflow, but I'm not sure what to call it, so I can't find it.

How would I make a "loop" for the C# program, that runs every, say, 100 milliseconds? Similar to what Minecraft calls "ticks", or GameMaker calls "steps".

I can't figure out how to do this. I'm using visual studio, and I have a main window. There are things that I want to execute constantly, so I'm trying to figure out how to make a "step" or "update" function.


回答1:


If you want it to run for 100 ms you would do this

System.Timers.Timer timer = new System.Timers.Timer(100);
public void Initialize(object sender, EventArgs e)
{
  timer.Elapsed+=Elapsed;
}
public void Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
  //do stuff
}

Something else you can do, however I don't think this one is as efficient

        using System.Threading;

        Thread th = new Thread(new ThreadStart(delegate
        {
            while (true)
            {
                Thread.Sleep(100);
                //do stuff
            }
        }));

Or, you can download monogame to make more elaborate games in c#

http://www.monogame.net/

It has its own gameTime control.




回答2:


Are you thinking of a Timer?

http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx

Generates recurring events in an application.




回答3:


You could use the Timer control which can be set to tick at a given interval. The interval property is in Milliseconds so you would need Timer1.Interval = 100;



来源:https://stackoverflow.com/questions/18338251/how-do-i-make-a-loop-for-a-game-that-runs-every-number-of-milliseconds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!