When to use actors in libgdx? What are cons and pros?

Lord_JABA picture Lord_JABA · May 16, 2012 · Viewed 14.4k times · Source

I'm writing simple solar system simulator. This is my first libgdx project. I'm using a Stage and Actors for the main menu and is pretty handy especially touch events handling. But ... looking at the examples i see nobody uses actors in actual game logic. I wander if i should use actor as a parent of planet class or just write my own class tor that. The planets won't be touchable and they will be moved only between the frames so the third parameter of action MoveBy will have to be time between frames. That are the cons. What are the pros for using Actors?

Answer

broken-e picture broken-e · May 22, 2012

The main pros for Actors are Actions, Hit testing and touch events, and Groups of Actors.

Actions make quick and easy tweening if your game logic needs that.

You can call stage.hit(x, y) at any time to return the first actor that returns true to whatever hit logic you wrote for it (usually checking bounds with x, y, width, height). return this actor or null to keep iterating through the actors' hit methods looking for a hit actor. Null is returned if no actor is hit.

Hit is used for the Stage's touch events. The actor's touch methods are passed local coordinates, and the Stage handles overlapping of objects, e.g. if an actor covers another actor such that the other actor shouldn't receive touchDown, return true on the covering actor to stop the calling of touchDown on actors "beneath". This also sets 'focus' on the actor that returns true so that Actor's touchUp will be called.

You can group actors together to perform Actions, touch events, etc on the entire Group of Actors as a single unit.

Some Cons: Actors require a stage which limits functionality somewhat. Many coders use other logic to determine game object state, rather than the scene2d Actions (e.g. box2d). If you use Actors for game objects, you will probably want two Stages, one for ui and one for game world. If you don't use them you'll probably be using your own SpriteBatch and Camera anyway though. And keep in mind that Actors only have an abstract Draw method so you will still need to create draw logic anyway. You'll probably keep a TextureRegion or Sprite as a private field for the Actor. If you want to use your own update logic, you can override the act(float delta) method to get the delta time (call super.act(delta) if you use Actions).

So if you have your own logic and won't use much of what Stage has to offer, save some resources and roll your own application-specific solution. If you can use some of the pros without limiting needed functionality then go for a second Stage for the game logic.