How do I make a “loop” for a game, that runs every

2019-09-03 05:41发布

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.

3条回答
Summer. ? 凉城
2楼-- · 2019-09-03 06:38

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.

查看更多
Ridiculous、
3楼-- · 2019-09-03 06:39

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;

查看更多
仙女界的扛把子
4楼-- · 2019-09-03 06:41

Are you thinking of a Timer?

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

Generates recurring events in an application.

查看更多
登录 后发表回答