Eugene S
Eugene S

Reputation: 99

How do I know if Scene2d actor has Stage coordinates or local to Group

When we have an Actor in Scene2d it seems that it doesn't know which kind of coordinates it has. Say, we need Actors Stage coords. So, if it's an Actor added directly to Stage then it will have a Stage coordinates, so we should't convert it. But when actor belongs to a Group it will have Group-local coords and these should be converted. Is there a way to know whether coords should be converted or not?

For actors added directly to the stage actor.getParent() != actor.getStage(); So that approach wouldn't work.

There is a 2D game. I have a ClickListener on SphereActor, with touchDragged method, where I get all the actors 'under' (in terms of z-index) the dragged SphereActor. So if we drag SphereActor and hover it over the magnet (on z-axis), it sticks to the magnet. So pseudo code would looks like this:

 public void touchDragged(InputEvent event, float x, float y, int pointer) {

 Actor hit = getActorUnderThis();
 SphereActor thisActor = (SphereActor) event.getListenerActor();

 if (thisActor.canBeAttractedBy(hit)) {//true for magnets
     thisActor.setPosition(hit.getX(), hit.getY()); //stick to magnet
 }
}

That approach works unless all our magnets belongs to Stage directly. Or with localToStage convertion would work when all our magnets are inside a Group.

But there are different types of magnets, some of them have animation, so I made them as a Group, and some of them are not, so they are connected to Stage directly. So to have the above code work I have to make it super ugly with

if (hit instanceOf AnimatedMagnet) {
// convert coords to stage before use
}

Now Sphere knows way too much about magnet implementation. And what if there hundred of different objects some of them in a group and some are not? Adding an instanceof check for each looks terrible.

So my question is mostly architecture-wise, what I supposed to do architecturally (to avoid too much knowledge of magnets in sphere), rather than just isBelongsToStageDirectly() method.

Upvotes: 0

Views: 192

Answers (1)

Akasha
Akasha

Reputation: 235

You can check to see if an Actor's parent equals the root Group of the Stage.

When a Stage is created it creates a Group instance called root to add actors to. See the constructor in Stage.java to see it initialised automatically https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/scenes/scene2d/Stage.java

So you can do something like if (hit.getParent() == stage.getRoot()) { // this is something added directly to the root of the stage }

In case you get into nesting Groups n number of times you can recursively check the parents with a while loop until you get to the stage root.

Upvotes: 1

Related Questions