1 TimingInDepth
Tim Young edited this page 2017-10-02 00:36:02 +02:00


The Sprite controller uses a System.Windows.Forms.Timer. This timer is notoriously un-precise, but it is very easy to set up initially. The timer in the SpriteController tries to fire off every 10 milliseconds, but it can fire off incredibly slowly if you have long pieces of code. You want all your functions to run as quickly as possible to avoid things looking jerky.

Most programs you will make using the SpriteLibrary will begin by tapping into the DoTick Event. Every time the sprite controller is ready to pass control back to your program, it will call the DoTick event. You want to see if you should be doing anything, and then exiting the do-tick function.

How to program a delay.

If you want to wait a little bit, you might think you could do a Thread.Sleep. This has the side-effect that it blocks the sprite-controller and the user-interface. Neither one of those can do anything while the thread is sleeping. Instead, you should have a DateTime variable that is set to the time you want to delay to, and have something like this in your DoTick:

If(DelayUntil > DateTime.UtcNow) return;

You can then set your delay with something like:

DelayUntil = DateTime.UtcNow + TimeSpan.FromMilliseconds(100);

This sort of delay allows everything to continue to function. The spritecontroller continues to check for events, the User Interface still updates, etc. And, since the timer is not precise, a counter that counts down from 1000 may have different amounts of time pass. We use the DateTime.UtcNow, instead of DateTime.Now, mainly in case someone is playing your game when daylight-savings happens. DateTime.Now will lose, or gain an hour. That can do strange things to your game.