5

如何在 libgdx 中按名称获取演员?

我目前有以下 ChangeListener:

    ChangeListener colorPickerListener = new ChangeListener()
    {
        public void changed(ChangeEvent event, Actor actor)
        {
            //Popup Window
            toolboxStage.addActor(blockWindow);
            //toolboxStage.getRoot().removeActor(blockWindow);
            Gdx.app.log("LevelEditorScreen", "Color Picker Selected");
            Gdx.app.log("LevelEditorScreen", "HUD Width: " + HUD_WIDTH);

            Gdx.input.setInputProcessor(toolboxStage);
        }
    };

上面的演员是被感动的演员。一旦这个特定的演员被触摸,我需要改变另一个演员的颜色。我究竟如何才能得到那个演员的名字?

4

3 回答 3

20

我想指出,已经有一种方法可以Actor按名称查找。

它的工作原理是这样的:stage.getRoot().findActor(name).

无需自己实现。:)

于 2014-01-18T09:20:06.573 回答
3

首先,您需要为您的 Actor 设置一个名称:(Actor#setName

myactor.setName("myactor");

然后你可以得到这个舞台中的所有演员,就像这样:( Stage#getActors )

Array<Actor> stageActors = mystage.getActors();

然后,您可以使用Actor#getName检查该名称的所有 Actor:

int len = stageActors.size;
for(i=0; i<len; i++){
    Actor a = stageActors.get(i);
    if(a.getName().equals("myactor")){
        //a is your Actor!
        break;
    }
}

但是,如果您保留对所有 Actors 的引用并使用它来代替它会更容易更高效。

于 2014-01-18T02:43:49.353 回答
1

我会推荐使用 Group 已经提供的功能。每个阶段都有一个根组,这实现了按名称查找演员。如果您使用分组系统,它的代码比答案内部给出的更安全。

Group 的代码看起来像这样并且更安全,因为如果您将组添加到阶段,它也会看起来在组内部。

    /** Returns the first actor found with the specified name. Note this recursively compares the name of every actor in the group. */
    public Actor findActor (String name) {
            Array<Actor> children = this.children;
            for (int i = 0, n = children.size; i < n; i++)
                    if (name.equals(children.get(i).getName())) return children.get(i);
            for (int i = 0, n = children.size; i < n; i++) {
                    Actor child = children.get(i);
                    if (child instanceof Group) {
                            Actor actor = ((Group)child).findActor(name);
                            if (actor != null) return actor;
                    }
            }
            return null;
    }

链接到小组课程

如果您需要搜索很多次以保持对 Actor 的引用。如果不只是使用 serch 方法。

于 2014-01-18T10:08:14.283 回答