I've created a hex tile map and I a problem in combining two features: 1) scrolling the map by dragging with the mouse/finger 2) highlighting a tile on mouse over position
My world contains a map, which consists of custom Tile() objects. Each Tile has an x and y coordinate saved. In my game class I use an OrthographicCamera and a TileSelector, a class that gets the current mouse position and highlights the appropriate tile underneath those coordinates. Further more, my render() method checks whether the mouse/finger is down and if so, each tile's position is updated by the distance moved while finger/mouse button down.
The following code shows the relevant parts. As long as I don't move the map, the highlighting works. But as soon as I do move the tiles, the highlighting starts to be off (by the amount of the distance moved).
//initialiting orthographic camera
camera = new OrthographicCamera(800, 480);
camera.setToOrtho(false, 800, 480);
//draw screen black
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
game.batch.setProjectionMatrix(camera.combined);
//drawing to batch
game.batch.begin();
//drawing the tiles, simply getting x,y coords and putting on screen
world.render(game.batch);
//highlighting tile under the current mouse/finger coords and drawing highlight on screen
selector.select(Gdx.input.getX(), Gdx.graphics.getHeight() - Gdx.input.getY(), game.batch, world);
game.batch.end();
//scrolling routine
if (Gdx.input.isTouched()) {
Vector3 touchPos = new Vector3();
touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(touchPos);
deltaX = (float)Gdx.input.getDeltaX();
deltaY = (float)Gdx.input.getDeltaY();
//moving each tile by the distance moved
for(int i = 0; i< world.getMap().getWidth(); i++){
for(int j = 0; j< world.getMap().getHeight(); j++){
tile = world.getMap().getTile(i, j);
tile.x += deltaX;
tile.y -= deltaY;
world.getMap().setTile(tile, i, j);
}
}
}
See screenshots for visualization:
1)Map not moved, mouse(red arrow) over tile and it is highlighted https://i.stack.imgur.com/3d7At.png
2)Map moved but mouse on old position, no tile should be highlighted, but the tile is highlighted as if the map has not moved https://i.stack.imgur.com/dSibc.png
Now I understand that the problem seems to arise from not mapping/updating screen and world coordinates correctly. But due to my lack of knowledge about LibGdx/OpenGL/projecting/translating I can't pinpoint my mistake. So can this rendering algorithm be fixed as it is? Or should I switch from moving my tiles to moving my camera(how)? Please let me know, if you need more of the code, thank you.