Accelerated game time with TimeSpan in C# - c#

I need to create an accelerated game time (presumably using a DispatcherTimer). I want 1 minute of 'real time' to equal 10 minutes of 'game time'.
Also, how would I set up gametime? Would this be a DateTime object? For example, let's say the game starts at 0600. Every 6 seconds I want the game time to increase by one minute.
How can I do this? Thanks!

GameTime is more likely to be a TimeSpan object which starts at zero and increments by as many seconds as you want by using its Add method. You would add 60 seconds to the TimeSpan object every time your "real world timer" registers a change of 6 seconds. Presumably you'd want to set your "real world timer" object up to notify you when each 6000ms has passed.

Related

Giving User A Reward When Certain Amount of Time Has Passed

During my game the user gets rewards every 10 minutes.
Even if they leave the app/game, when they come back, if 10 minutes has passed, they still get their reward.
So lets say for example: the user is playing and leaves the game with 5 minutes left until the next reward.
The user then leaves the game and returns an hour later.
How would I go about seeing if the 5 minutes have passed since the last open?
Does anyone know how to do this? I am using unity.
You may want to use DateTime struct, especially its DateTime.Now.
When your player leaves the game save the date time:
DateTime leaveDateTime = DateTime.Now;
//Store leaveDateTime value
When your player resumes,
//load leaveDateTime value
TimeSpan diff = DateTime.Now - leaveDateTime;
Then use your TimeSpan values (check TimeSpan.TotalMinutes) to give reward to your player.
if (TimeSpan.TotalMinutes >= 5){
//Give rewards for your players
}
Ian answer is OK but it has one problem, if user change the system (PC, mobile, ...) date and time, lets say add one year to the date, when he come back to game, he will get zillion reward unfairly! I think current dateTime must be recived from a ntp server instead of DateTime.Now.
Take a look at this answer : How to Query an NTP Server using C#?

Timer trigger before interval

I have something like the following:
myTimer.Interval = 100;
myTimer.Start();
...
In my myTimer_Elapsed(...) function something like the following:
DateTime.Now.TimeOfDay.ToString("g") written to a file.
Getting this as result:
System Time Now: 13:20:00,2959841
System Time Now: 13:20:00,3467621
System Time Now: 13:20:00,3789866
System Time Now: 13:20:00,4033991
System Time Now: 13:20:00,4356236
System Time Now: 13:20:00,4619891
I was expecting results bigger than 0,1 seconds because there are more process, and I was trying to calculate that impact, but I'm frustated because I don't know how can be even possible to have times lower than 0,1 seconds
Thanks in advance
What kind of timer do you use? If it's the Windows.Forms.Timer, it has a very limited accuracy .
The Windows Forms Timer component is single-threaded, and is limited
to an accuracy of 55 milliseconds. If you require a multithreaded
timer with greater accuracy, use the Timer class in the System.Timers
namespace.
Quoted from here: Windows.Forms.Timer

How to make precise clock in XNA?

I am making an XNA game and it's time to make daytime system and for that I need some kind of clock. I tried to use GameTime.TotalGameTime.Milliseconds == 0 to add one second to the second counter of my custom clock class, but it turned out that GameTime doesn't always run through zero milliseconds. Using TimeSpan prevUpdate to compare to TotalGameTime.TotalSeconds doesn't give enough precision, and the time is noticeably slower than the real time somehow.
What XNA or .Net component can I use to base my clock on so that it doesn't cost too much resources or deviates noticeably from real time?
Use Stopwatch for high-precision timing (reference).
Use XNA's GameTime for rendering and frame-to-frame timing logic. XNA's timer does not match "wall clock" time exactly. It is able to drift in order to better line up with frame rendering, giving you smoother animation (this is behaviour is provided by the Game class). Over time it will deviate from real time slightly, but for most games this is not a problem.
Use DateTime for measuring longer time spans accurately (eg: minutes, hours).
Note that you shouldn't compare Milliseconds == 0, because you cannot know exactly when XNA will call your Update method, so you could have Milliseconds == 999 on one frame, and then Milliseconds == 15 the next - wrapping around and skipping past 0, so your condition never triggers.
So you need to determine when the timer crosses the threshold. There are many ways to do this. You could track a threshold (useful if you are tracking some "total" time), incrementing it after each trigger. Personally I prefer to accumulate time like so:
seconds += gameTime.ElapsedTime.TotalSeconds;
if(seconds > 1.0)
{
seconds -= 1.0;
DoSomething(); // Triggered each second
}

C# - Time calculation not working with TimeSpan.FromTicks DateTime

I am trying to calculate a video framerate in a program. To do this I take
DateTime.Now
at the beginning of a stream, and then again after every frame whilst also incrementing a framecounter.
Then I calculate the FPS like so:
int fps = (int)(frames / (TimeSpan.FromTicks(CurrentTime.Ticks).Seconds - TimeSpan.FromTicks(StartTime.Ticks).Seconds));
The problem is that I occassionally get a negative number out, meaning the start time must be later than the current time. How can this be the case? Does anyone know anough about these functions to explain?
Seconds gives you the seconds part of the TimeSpan, not the total duration of the TimeSpan converted in seconds. This means that Seconds will never be greater than 60.
Use TotalSeconds instead
You should consider using StopWatch for such needs, It has much better precision
The datetime functions are probably not precise enough for your needs, you may want to look into performance counters instead. I think the StopWatch class is what your looking for. System.Diagnostics.StopWatch. that is using the QueryPerformanceFrequency and QueryPerformanceCounter functions for the timing.

Does Daylightsaving time cause DateTime calculations to become negative

We are currently rewritting the core of our services, basically we have scheduled tasks that can run on intervals, dates, specific times etc etc etc.
Currently we're wondering if daylightsaving might cause trouble for us, basically we calculate the next possible runtime, based on what days the task should execute and between what times, and what interval. We do this by taking the current time, and adding days/minutes/hours to this DateTime.
We then take this new run time and subtract DateTime.Now from this DateTime, leaving us with the timespan untill the next run.
How ever, what if the current time is 01:50 on a daylightsavings day, we add 20 minutes, which is our set interval, and end up with a time of 02:10, how ever since this is daylightsavinds, it's actually 01:10.
When i subtract the current time (01:50) from the 01:10 (which is actually 02:10) does this return a negative value which i need to work around or does this never ever return a negative value because DateTime is just a long underneath holding the proper information?
Basically, the following code, is the check needed or not?
//Get interval between nextrun and right now!
double interval = (NextRun - DateTime.Now).TotalMilliseconds;
//Check if interval is ever less or equal to 0, should never happen but maybe with daylight saving time?
if(interval <= 0)
{
//Set default value
interval = IntervalInMilliseconds;
}
We believe that this check isn't needed but our googling so far hasn't given us a definative answer.
Use DateTime.UtcNow instead of DateTime.Now EVERYWHERE
First of all, you can try it yourself as it will help you understand how it works.
Essentially, using your example above, if you have 20 minutes to a local time, it would be 2:10 and not 1:10 as the computation is done in local time. If you want to get 1:10, you need to convert local time to universal time, add 20 minutes and then convert back to local time.
If you want real elapsed time, then you have to convert time to universal time before computing time difference. Also, if you work in local time, you won't be able to differentiate ambiguous time when the clock goes back.

Categories