libgdx可点击对象?

时间:2019-06-05 12:50:48

标签: libgdx tiled

有人可以向我解释如何检测物体的点击吗?我已经看到了这个问题的答案,但是没有用。

public class TiledMapActor extends Actor {

    private TiledMap tiledMap;

    private TiledMapTileLayer tiledLayer;

    private TiledMapTileLayer.Cell cell;

    public TiledMapActor(TiledMap tiledMap, TiledMapTileLayer tiledLayer, TiledMapTileLayer.Cell cell) {
        this.tiledMap = tiledMap;
        this.tiledLayer = tiledLayer;
        this.cell = cell;
    }

}

public class TiledMapClickListener extends ClickListener {

    private TiledMapActor actor;

    public TiledMapClickListener(TiledMapActor actor) {
        this.actor = actor;
    }

    @Override
    public void clicked(InputEvent event, float x, float y) {
        System.out.println(actor.cell + " has been clicked.");
    }
}




public class TiledMapStage extends Stage {

    private TiledMap tiledMap;

    public TiledMapStage(TiledMap tiledMap) {
        this.tiledMap = tiledMap;

        for (MapLayer layer : tiledMap.getLayers()) {
            TiledMapTileLayer tiledLayer = (TiledMapTileLayer)layer; //THE ERROR IS IN THIS LINE
            createActorsForLayer(tiledLayer);
        }
    }

    private void createActorsForLayer(TiledMapTileLayer tiledLayer) {
        for (int x = 0; x < tiledLayer.getWidth(); x++) {
            for (int y = 0; y < tiledLayer.getHeight(); y++) {
                TiledMapTileLayer.Cell cell = tiledLayer.getCell(x, y);
                TiledMapActor actor = new TiledMapActor(tiledMap, tiledLayer, cell);
                actor.setBounds(x * tiledLayer.getTileWidth(), y * tiledLayer.getTileHeight(), tiledLayer.getTileWidth(),
                        tiledLayer.getTileHeight());
                addActor(actor);
                EventListener eventListener = new TiledMapClickListener(actor);
                actor.addListener(eventListener);
            }
        }
    }
}

Stage stage = new TiledMapStage(tiledMap);
Gdx.input.setInputProcessor(stage);

我已使用此代码尝试过此操作,但收到以下错误消息:

 com.badlogic.gdx.maps.MapLayer cannot be cast to com.badlogic.gdx.maps.tiled.TiledMapTileLayer

我不明白如何选择可点击的对象

1 个答案:

答案 0 :(得分:1)

您已经发现,问题出在这里:

for (MapLayer layer : tiledMap.getLayers()) {
    TiledMapTileLayer tiledLayer = (TiledMapTileLayer)layer;

看起来这些图层不是TiledMapTileLayer类型-或至少不是全部。 (Afaik在TiledMap中也有ObjectLayers。)让代码再次运行的最简单方法是检查一个instanceof:

for (MapLayer layer : tiledMap.getLayers()) {
    if (layer instanceof TiledMapTileLayer) {
        TiledMapTileLayer tiledLayer = (TiledMapTileLayer)layer;
        createActorsForLayer(tiledLayer);
    }