I have the main game loop in libGDX. On the touch() event I want an animation to be executed. So I will have a variable which will store the value which will be updated each frame and further rendered side by side each frame.

The problem: I want an another animation to take place after the first one finishes. How do I update variable to do so? Because it should take place after first. I can't place two statements in loop one after another. Is there a way to create an another game loop inside first so that when inner runs the outer is paused?


You would usually use an explicit state machine for that. The idea is that you have a variable that stores the current state (say: animation A). And when that animation finishes you update the state variable to a new state (say: animation B).

Then, in your loop, when playing animations, you have a switch satement that selects a case depending on the state variable, and then that case handles the logic for that state.

There are more advance solutions, of course. You might create your state machine as a tree, where each state has sub-states. You may represent them as data (they are not a bunch of switch statements, but dictionaries). Or you could use full-fledged behavior tree.

Alternatively, you might also use coroutines. A common trick is to implement them as iterators (each loop you pull a new item, and the logic is in the iterator), then you can build an implicit state machine around them.

And of course, you can mix and match. For example, have a state machine that picks a behavior tree.

There are also libraries that help you implement all that, you may want to have a look around. I do not really develop in Java. So, I can’t really recommend.

  • \$\begingroup\$ Java doesn't provide coroutines (at least not natively). OP would need to switch to a libraries that provides them (such as KTX) or code them. For something like this, I agree with your suggestion of using variable to track the state. \$\endgroup\$
    – Pikalek
    Jun 27 '19 at 22:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.