Endanke
Endanke

Reputation: 887

One swing timer at once?

I'm using a swing timer to animate a figure movement in my game. It's working fine if I send it from one point to another, but when I call it multiple times, the animation speed adds up.

I think it has to work this way, but can I "stack up" timers to only start the upcomming when the current animation finished?

It's not the exact code but works like this:

Timer timer = new Timer(40, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(figure.x != target.x){
                    if(figure.x < target.x){
                        figure.x+1;
                      }else{
                    figure.x-1;
                }
        }
 }
});
timer.start();

Upvotes: 0

Views: 136

Answers (2)

JVMATL
JVMATL

Reputation: 2122

There are a few things you can do here:

  • run the timer all the time (most of the time it does nothing, unless target changes) Simple to understand, moderately inefficient if lots of things are moving at once, but probably ok for a small number of animations.
  • make your movements time-based (i.e. instead of just moving by one 'pixel' every time the timer ticks, plan your target destination and arrival time and then when the timer ticks, calculate where your figure should be right 'now' and move him there.
  • attach a volatile flag to your object that lets you know he already has a timer attached, so that you don't attach multiple timers to the same object.

Aside: there is no way to 'queue up' timers the way you are thinking, to show one animation at a time. You will need more framework code outside of timers for that. (e.g. use a linked list to maintain a queue of movement events, and when one movement finishes, the timer task pulls the next movement off the queue and starts working on that..)

Upvotes: 4

trashgod
trashgod

Reputation: 205875

Use a separate instance of javax.swing.Timer for each distinct period that is not a multiple of the fundamental animation rate. All instances share a common queue. Usually only a few are needed; 25 or so is a practical limit.

Upvotes: 3

Related Questions