How to calculate the index of the tile underneath the mouse in an isometric world taking into account tile elevation

Viewed 1410

I have a tile-based isometric world and I can calculate which tile is underneath specific (mouse) coordinates by using the following calculations:

function isoTo2D(pt:Point):Point{
  var tempPt:Point = new Point(0, 0);
  tempPt.x = (2 * pt.y + pt.x) / 2;
  tempPt.y = (2 * pt.y - pt.x) / 2;
  return(tempPt);
}

function getTileCoordinates(pt:Point, tileHeight:Number):Point{
  var tempPt:Point = new Point(0, 0);
  tempPt.x = Math.floor(pt.x / tileHeight);
  tempPt.y = Math.floor(pt.y / tileHeight);
  return(tempPt);
}

(Taken from http://gamedevelopment.tutsplus.com/tutorials/creating-isometric-worlds-a-primer-for-game-developers--gamedev-6511, this is a flash implementation but the maths is the same)

However, my problem comes in when I have tiles that have different elevation levels: enter image description here

enter image description here

In these scenarios, due to the height of some tiles which have a higher elevation, the tiles (or portions of tiles) behind are covered up and shouldn't be able to be selected by the mouse, instead selecting the tile which is in front of it. How can I calculate the tile by mouse coordinates taking into account the tiles' elevation?

I'm using a javascript and canvas implementation.

4 Answers
Related