Creating smooth animations with C# across distinct computer techniques can be a demanding undertaking. Having said that there is a very simple strategy to change a program actions to a focus on number of frames per 2nd.
Animating objects with C# can signify a number of distinctive points.
To start with would be animating a sequence of image pictures like an animated GIF. In this scenario there is by now some existing aid in the .Web Framework, but most likely you want to tackle drawing on a frame-by-frame foundation.
A different form of animation is with code-generated photos. GDI%2B can attract some really complicated graphics and animating them efficiently can bring an added dimension of high quality to your .Internet applications.
Finally from time to time programmers want to animate Window Type habits, this sort of as dimensions, place, text, etc. Even though these are item houses, we want them to alter within just a common interval, no issue what the velocity of the personal computer CPU is.
The initial action for crafting regular FPS animation in C# is to determine the way to measure CPU cycles. The most frequently utilized objects to measure time is the Timer object and the DateTime class. When equally are effortless to use, they lack accuracy. Alternatively, we are heading to make use of the Method.Diagonistics.StopWatch course.
The StopWatch class utilizes the API phone QueryPerformanceTimer to continue to keep keep track of of CPU cycles, which is additional correct. Better precision in this situation indicates a additional continual animation.
Basically you will want to hold observe of three values, two of which will modify constantly:
- Interval = Stopwatch.Frequency / [target FPS (30.0 for example)]
- currentTicks = Stopwatch.GetTimestamp()
- lastTicks = exact as currentTicks but taken the very last time the animation was drawn
The logic behind the C# algorithm is not also difficult. In nutshell, a loop will be frequently running, but you only want the animation to execute/refresh when the previous number of CPU cycles and the recent amount of cycles has at minimum a gap of the Interval you beforehand calculated. Then and only then is the animation refreshed.
The result is a continual animation no make any difference how fast a laptop or computer is. Merely modify the FPS in your individual system and that will be the perceived pace throughout programs.
The rationale it works is since animations are not operate on a simple whilst/for loop brainlessly. The loop makes use of the host computer’s CPU cycles to adjust the interval the animation is refreshed.