I’m making a platformer I’m trying to make it frame rate independent. I have a vague understanding of gameTime and how to use it, but I’m still confused of when to use it, and all attempts so far to implement it haven’t worked. My two questions are thus:
When should I use gameTime, do I use it for friction as well as change in velocity? And can I just do all of my calculations on the change in coordinates then multiply the final vector by gameTIme.ElapsedGameTime.Seconds or do I have to multiply each calculation?
How do I properly implement? A code snippet of a basic physics system with it implemented would be really helpful too.
Couple things to understand about gameTime:
The .Seconds property only represents the seconds “remainder value”. I.e. if your ElapsedGameTime was 10.5 seconds, the Seconds property would have a value of 0.5s. The TotalSeconds would have a value of 10.5, which based on your comment seems to be what you want here. Same goes for the other properties like Milliseconds and TotalMilliseconds, which is probably what you actually want to be using, but up to you.
However, you won’t see any change in your game’s execution with this code by default unless its framerate falls under 60fps. This is because MonoGame limits your game loop cycles to 60Hz by default (60 FPS). You can release this limit by setting IsFixedTimeStep = false in your game’s constructor (or later if you want to keep a fixed timestep for your loading cycle or some such). Be aware that doing so can have your game run at hundreds of frames per second during points where it isn’t doing much. Meaning, you need to consider the possibilities when using gameTime to animate things where the TotalMilliseconds value is very very small.
How you calculate that is up to you. I don’t have much of an opinion on it without seeing your code. Whether or not it is appropriate to apply the gameTime modifier to your end-result vector or to each portion of the vector’s calculation depends on how exactly you’re implementing those changes (percentages, +10 directly, based on duration of a button press, etc).
In essence, use gameTime code (deltaTime) when things change over time in your world:
Velocity adding onto position → use deltaTime
Acceleration affecting velocity → use deltaTime
Friction affecting velocity → use deltaTime
Setting velocity to a constant → DON’T use deltaTime (I explain next)
If you look at how I implement jump in the link, I set the velocity as such:
When I set the value to a constant rate, I don’t need deltaTime. However when I add the velocity onto position, I still need to use deltaTime.
Another thing to note is some things don’t need deltaTime, such as mouse movement over time. Say for example, you create a camera that pans or rotates when you move the mouse. In this case, you don’t use deltaTime: