Search code examples
libgdxactorstage

Understanding coordinates in libgdx


I'm currently working on a libgdx project. This is the structure I'm following:

Single Game - several screens - each screen has a stage - each stage has some groups - each group has some actors - each actor has an sprite.

I'm playing with dragging actors between the groups, but when I'm adding actors into a group, the coordinates are always 0,0 even if I specify others.

I've read something about local coordinates and stage coordinates.

The quesion is... how can I add an actor (and its sprite) in the middle of the group?


Solution

  • After adding an actor into group, coordinates of actor became relative to group. If you know width and height of group, you can use following code snippet if your actors origin is on its (0,0) point :

    group.addAtor(actor);
    actor.setX(group.getWidth() / 2 - actor.getWidth() / 2);
    actor.setY(group.getHeight() / 2 - actor.getHeight() / 2);
    

    If you set the origin to actors central point like below :

    actor.setOrigin(actor.getWidth()/2, actor.getHeight()/2);
    

    then you can use following code without considering actor's width and height :

    actor.setX(group.getWidth() / 2);
    actor.setY(group.getHeight() / 2);