LibGDX: shiny new actions!

If you've been following my latest series of articles, I posed a question about the best way to do some things in LibGDX, and then shared the process I went through in coming to an answer. With the help of Nathan Sweet (the committer kind enough to humor my rambling and pull requests), all that work resulted in Fresh New Code being added to LibGDX! This is the sort of collaboration that I love about open source projects. It helps the code evolve and stay relevant, and (the reason I'm busy typing this up and writing example code and drawing graphs) it helps the community as a whole improve their familiarity with the tools.

The Actions

Anyway, enough preamble: allow me to introduce you to CountdownEventAction (available now in the LibGDX nightlies).

The purpose of CountdownEventAction is simple: to listen for a specific kind of event and wait until it receives count number of them. This simplicity grants a great deal of flexibility because the Event system itself is so powerful. The example code I wrote uses it to sequence actions that are spread across different actors, but you could as well link it to UI interaction, game processes like AI, whatever you can imagine really!

CountdownEventAction itself is built on a new abstract class, EventAction. EventAction implements the "listening for events" logic, so if you don't need the "wait for X of them" behavior, you can subclass EventAction and build from that.

Usage Notes

If you're familiar with how events bubble up through Scene2D's actors, you'll know it's important to keep in mind which actors are firing events and which actors are listening for them. EventAction – once added to an actor – will listen for events that bubble up through that actor.

The other thing to keep in mind is that EventAction is designed to only listen while it's active. EventAction considers itself not active by default and then becomes active the first time act(float delta) is called upon it. If you imagine your EventAction is just one action in a sequence, it's only listening once all the previous actions have completed, and isn't active after it gets restarted. I hope this is intuitive; I think it follows the principle of least surprise. If you really want your event to be listening all the time, you can always add it in parallel to other actions, or just implement an EventListener directly.

So that's it! Simple, yes. Small, yes. But I think it's an elegant and powerful tool to have in the toolbox. The power of event-based systems to decouple code is something that has been well covered, and this gives you more options for building with such a system.