I have two variables: counter
and frequency
. I am using these two variables as such:
counter = counter >= frequency ? 0 : counter + 1;
As you can see, the counter counts up, until the point it matches the frequency, and then it resets to 0. At the moment, frequency
is set to 100
. So the counter should reach 99, and then reset to 0.
I am using this counter to rotate an image at a rate of 100 times a second:
private int counter = 0;
private int frequency = 100;
private DispatcherTimer dispatch = new DispatcherTimer();
public Timer()
{
this.dispatch.Interval = TimeSpan.FromMilliseconds(1000 / frequency);
this.dispatch.Tick += new EventHandler(updateTimer);
this.dispatch.Start();
}
private void updateTimer(object sender, EventArgs e)
{
counter = counter >= frequency ? 0 : counter + 1;
saveImage.RenderTransform = new RotateTransform(counter * 3.6);
}
The script will rotate the image around a 360 degree plane. Since frequency is set to 100, it will go the full 360 degrees, since 100 * 3.6 is 360. This works great if the frequency is set to 100. However, if I change the frequency, it may not go the full 360 degrees; or it may even go more than 360 degrees.
A simple fix to this would be to change the rotation math to the following:
saveImage.RenderTransform = new RotateTransform(counter * (360 / frequency));
However, doing this in actuality produces an odd result. The image never reaches the full 360 degree turn; and instead only reaches 300 degrees, before it eventually resets to 0. What is wrong with my math here?
Debug.WriteLine(counter * 3.6)
and see for yourself? – CodeCasterc * (360 /f)
will use integer operations.360/100 -> 3.6 -> 3
– Marc B