Timers

I’m looking for the best way to make a reload system a gun in my game, however, i’m not sure about the best way to go about this. I know there is a timer variable, but i’m unsure of how i should use it. Or possibly I should use nanotime(), I don’t know. Any input on this conundrum?


private long reload = 2000; //2 sec

public void update(long delta){
//update logic
reload -= delta;
if (reload <= 0){
reload = 2000;
player.reload();
}
}

ReBirth has the right idea here. I always use delta timing.

Hi

I hope I really understand what you mean. Personally, I recently succeeded in implementing the selection of a weapon (the “put back” and the “pull out”) and the reload in my first person shooter. As you talk about a gun, I assume we speak about the same thing.

At first, if you plan to use nanotime or currentTimeMillis, you will need a “hack” to force the use of an high precision timer under Windows:
http://bugs.sun.com/view_bug.do?bug_id=6435126

Secondly, princec already explained how to use a timer in general and it is used in that way in Ardor3D as far as I know. At each iteration:

  • update the timer itself
  • update the whole logic
  • render

Thirdly, I assume Rebirth’s suggestion uses as a parameter the period between 2 frames in seconds (or time per frame). It should be enough.

Finally, I use a more complicated system in order to prevent the player from doing absurd things. For example, you don’t want to allow your player to reload and select another weapon at the same time or to reload and attack at the same time. That’s why I use a state machine with a kind of “scheduler”. I will probably publish an article about that in my blog soon, it is a bit difficult to explain it without a schema.

If you want to follow mine, maybe you can make a separate class to handle timing. But my pseudo one is enough for simple case.

Look, a tutorial! :slight_smile:

Get yourself a good game timer. From the main timer, call each of your entities or whatever with some update function (with a variable timestep, pass in the delta, with a fixed timestep, pass in nothing). Then have a local value (a float or long or whatever) and in a variable timestep add the delta every frame. In a fixed timestep, add the global delta. When this local value is >= the amount of time you want to wait for, do something.

All done.