Creating my own Timer ( libgdx)

Heya guys! Im trying to create a class that i can pass the seconds i want it to wait as a param and every update of the Class that has the Timer as a variable, the update() of timer is called.

Heres what i have until now, its almost nothing but idk how to do it :

package br.tools;

/**
 * @author André Lopes
 */
public class MyTimer {

    private int currentSecond;
    private int secondsToWait;

    //Float Delta as param@ ???
    public void update() {
    }

    public boolean hasFinished() {
        return currentSecond >= secondsToWait;
    }

}

Can you maybe…reword that? I don’t quite get what you are trying to accomplish.

Oh sure,

The objective is to have an object that i can use to count seconds. And return true if the seconds that i passed to the contructor have passed since the first update call :stuck_out_tongue:

Get it?

its a simple timer :stuck_out_tongue:

Rather than use a timer just store an int or long representing when an event ends.

// Schedule an event
timeOfThing = now + 5000; // 5000 ms - could also be ns or ticks
...
// Has it finished? now is updated once per loop iteration.
if(now >= timeOfThing) { ... }

Well, you couldn’t really pass information to the constructor after the object is created. A timer can be as simple as this:

public class Timer
{
    private final long NANO = 1000000000; // Number of nanoseconds in a second
  
    long start; // Tracks when the timer was started
    long end;  // Tracks when the timer ends
    
    long seconds; // Number of seconds to wait
    public Timer(int seconds)
    {
        this.seconds = seconds * NANO;
        start = end = -1; // I use negative one to see if the timer is active
    }

    // Activate the timer
    public void start
    {
        start = System.nanotime();
        end  = start + seconds;
    }

    // Check if the timer is done
    // If so, deactivate it and return true
    public boolean isDone()
    {
        if (start > 0 && end > 0)
            if (System.nanotime() >= end) {
                start = end = -1;
                return true;
            }

        return false;
    }
}

Add a setter method for seconds, and you can use a single instance of this timer multiple times for different things. Each time you can start, it effectively “resets” the timer.

I work with System.nanoTime() because it tends to be more accurate that System.getCurrentTimeMillis().

More libGdx way, using TimeUtils.


public class Timer
{
    private long start;
    private long secsToWait;

    public Timer(long secsToWait)
    {
        this.secsToWait = secsToWait;
    }

    public void start()
    {
        start = TimeUtils.millis() / 1000;
    }

    public boolean hasCompleted()
    {
        return TimeUtils.millis() / 1000 - start >= secsToWait;
    }
}

Hope it works.

Thanks guys! I implemented the timer and hm, now im working on the rest of my list of objectives to this week!

Im having problems with camera, but i think i would need to make another topic… I will try a bit more before post!

FWIW, libgdx has a Timer in the utils package. It is similar to java.util.Timer but runs the tasks on the game thread and the tasks can be reused to avoid allocation.

I don’t know why you would use a timer class in a game. Can someone explain it to me? It just seems like creating a Multiplication or Addition class, since timestamps only involve addition and subtraction. It makes sense in an event queue system like AWT, but it seems unnecessary outside of a message passing application. It’s too much to think about and too much overhead. I would rather program in a system that looks like the rest of my game loop, performing updates once per turn, than one that looks like AWT. Timestamps are just simple and there is nothing to keep track of beyond one primitive variable.

Your little code example could be considered a timer. You set a time you want something to happen, then every frame you check if you’ve reached that time. That’s what you call a timer. Yes, it updates per frame, but that just means the time units is in frame count rather than seconds or milliseconds.

Besides that, if you have non-consistent frames rates, that would mean your events would happen at variable times. Or you could go and account for that, but at that point, you are no better off than if you had just used a simple timer class. And I don’t see how you get 5000 “ms” or “ns” when you are updating at a rate of once per frame. To accomplish that, you’d have to synchronize your entire game to match your frame rate to that value.

Finally, your example takes more than one variable, because you need an accumulator to keep track of the ‘now’ variable that you are comparing to “timeOfThing”. At that point you are using 2 variables, which is all my Timer class is using (exclude the one that just holds how long to wait for, which you’ve hard coded).

Just because something is in a class, doesn’t mean it’s more complicated or causes overhead. It’s Java. It’s OOP. That’s how you are suppose to program. A timer object can be re-used just as easily as a single variable.

At least, all this is just my thought process.

I plan that my player will be poisoned and be poisoned for like 5 seconds.

Code re-usability and general object oriented practices.

Common scenario for beginner programmers:

You want to hide a sprite after N time. You end up writing some timer code to do that:

if (mysprite.isVisible() && myspriteTimeElapsed > myspriteDuration) {
   mysprite.setVisible(false);
}

As your game grows, you want to apply this to other sprites. Then, maybe you want to affect other attributes over time, like color or position. Eventually you end up with a lot of “spaghetti code” and lots of copy-pasting.

If you decide to change your timing function later on (for example, to support easing functions) then you will have a lot of tedious refactoring ahead of you.

On the other hand, if you had just used classes from the beginning, you would only have to change a few lines of code.

The point is to think abstractly when designing a game architecture. If you are implementing a feature, like fading a sprite out over 1.0 second, think about how you can abstract it. Then, the abstraction can be re-used through other parts of your application.

Here is a practical example of a basic timer with easing functionality:

(In LibGDX it would be best to use their Interpolation, Actions, or Timer utilities depending on your needs.)

Thanks for the responses. I will read them more thoroughly later.

Well I would not use static variables. I already have a entity class that stores other instance specific state data.


public void update(long ticks)
{
  if (isVisible() && ticks > scheduledInvisibleTime) setVisible(false);
}

Of course it is not spaghetti code at all. There is no change in control flow beyond an if or while statement. There are no function calls to a function or callbacks unlike with additional objects. There is also no spooky action at a distance effect, so it would be much easier to debug.

[quote=“davedes,post:12,topic:44037”]
If I chose a unit of time I would never change it in the middle of my project. I use ticks for state updates and floating point (delta) time for graphics. I integrate velocity and acceleration to get interpolated sprite positions between updates. draw(tick, 0.0f) draws the object where it is as of the last update and draw(tick, .9999999f) draws it where it will be at the beginning of the next turn. If an easing function can be expressed as a function of time I just take the difference between the current time and a timeStamp which gives me t for f(t).

If I want to make a satellite fly across the sky, blink, and change color I do this, what would you do?


public class Satellite extends Entity
{
  private final long startTime;
  private final double colorPeriod;
  private final double blinkPeriod;

  public Satellite(double x, double y, double colorPeriod, double blinkPeriod, long tick)
  {
    this.x = x; this.y = y;
    this.vx = 4;
    this.vy = 1;
    startTime = tick;
    this.colorPeriod = colorPeriod;
    this.blinkPeriod = blinkPeriod;
  }

  public void update(long tick)
  {
    x += vx; y += vy;
  }

  public void draw(long tick, double delta)
  {
    // If either of these were not a one liner, it would go in a static function or enum.
    double hue = 360.0 * ((tick + delta) % colorPeriod) / colorPeriod;
    double lightness = square(sin((tick + delta) / blinkPeriod));
    // Not functions from a real library. I will eventually stop using Java2D.
    setHSLColor(hue, .75, lightness);
    drawImage(x + vx * delta, y + vy * delta);
  }
}