Picking the 'top' tile in isometric games (images included)

I’ve recently written a small isometric game renderer, which for all intents and purposes seems to work fine.

However, when it comes to ‘picking’ the tile under the mouse cursor, I’m encountering some issues.

When hovering the mouse over a tile in the scene, it seems to pick that tile’s coordinate fine. I then render a ‘selection box’ over the top-most tile at that coordinate:

However, when I extrude the terrain upwards, I can’t quite work out how to make this picking algorithm work beyond just one layer, leading to the wrong tiles getting picked under the mouse cursor:

The way the world is built is by having a 2D array of integers that determine the ‘height’ of the column of tiles at that coordinate. So cell 0,0 might have a height of 6 tiles, and cell 3,4 might have a height of 7 tiles. When rendered, each vertical column of tiles is drawn from back-to-front.

Here’s my current picking code:



// mx: The X coordinate of the mouse (in the world, offset by the camera X position)
// my: The Y coordinate of the mouse (in the world, offset by the camera Y position)
// hoverCell: A Point object storing the hovered-over (2D) world coordinate
// tileRenderSize...: These values represent the width, height (and half widths / heights) of the tiles in the scene

private void getHoverTile()
	{
		int mx = (int)((Mouse.getX() + camX) - tileRenderSizeWidthHalf);
		int my = (int)((Engine.DISPLAY_HEIGHT - Mouse.getY()) + camY);
		
		hoverCell.x = (int)(mx / tileRenderSizeWidthHalf + my / tileRenderSizeHeightHalf) / 2;
		hoverCell.y = (int)(my / tileRenderSizeHeightHalf -(mx / tileRenderSizeWidthHalf)) / 2;
		
		// bounds check
		if (hoverCell.x < 0) hoverCell.x = 0;
		if (hoverCell.x > width-1) hoverCell.x = width-1;
		if (hoverCell.y < 0) hoverCell.y = 0;
		if (hoverCell.y > depth-1) hoverCell.y = depth-1;
	}

Would anybody be able to shed any light on how I can effectively pick the right tile on ‘top’ of each column of tiles? At the moment it only works for one layer! :frowning:

Thanks in advance for any advice anyone can offer!
~Pixel