如何为平铺地图中的切片添加点击侦听器,以便在使用鼠标选择切片时它会突出显示?
答案 0 :(得分:21)
libGDX不直接支持,因为TiledMap的东西仅用于渲染。
您可以轻松创建Stage
,它将作为TiledMap的某种叠加输入层。只需为每个图块创建一个Actor
,其大小与该图块的位置相同。然后,您可以将EventListener
添加到这些演员,以便能够识别这些演员的点击等内容。
这些演员应该提及他们的“起源”,即TiledMapTileLayer.Cell
。因此,您可以在处理这些事件时随时从演员返回到单元格。
以下说明了如何执行此操作:
此Actor负责捕获事件并保留基于以下内容的信息:
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.");
}
}
以下类实际上从给定的地图创建actor并将它们连接到侦听器:
public class TiledMapStage extends Stage {
private TiledMap tiledMap;
public TiledMapStage(TiledMap tiledMap) {
this.tiledMap = tiledMap;
for (MapLayer layer : tiledMap.getLayers()) {
TiledMapTileLayer tiledLayer = (TiledMapTileLayer)layer;
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);
}
}
}
}
现在TiledMapStage
将为您完成所有工作。您需要做的就是:
Stage stage = new TiledMapStage(tiledMap);
Gdx.input.setInputProcessor(stage);
在渲染(...)中,您需要调用stage.act()
。请记住对舞台使用相同的Viewport
来渲染TiledMap。否则,输入和渲染的地图将不会对齐。