Screen space to Isometric space in AS3

On 2.1.2013 by Antti Lepistö

How to turn screen space point into a point in isometric space? Well, here’s how: Vector_p is the point we clicked. Vector_u_len and vector_v_len are the values we’re looking for.

 

iso_grid_logic

 

Dot product gets us angle A between vectors up and p. We know that angles A and B make 60 degrees (or π/3) in isometric projection so we can figure out rest of the angles easily. As vector_p, A, B and G are now known law of sines gets us lengths of the other two sides (vector_u_len and vector_v_len).

Now int(vector_u_len / vector_up.length) gives us the row and int(vector_u_len / vector_right.length) the column.

private function onClick(evt : MouseEvent):void
{

var vector_p : Point = new Point(evt.localX, evt.localY);
var vector_up : Point = new Point(Cell.CELL_WIDTH * .5, -Cell.CELL_HEIGHT * .5);
var vector_right : Point = new Point(Cell.CELL_WIDTH * .5, Cell.CELL_HEIGHT * .5);

var dotProduct : Number = vector_p.x * vector_up.x + vector_p.y * vector_up.y;

var rad_a : Number = Math.acos(dotProduct / (vector_p.length * vector_up.length));
var rad_b : Number = (Math.PI / 3) - rad_a;
var rad_g : Number = Math.PI - rad_a - rad_b;

var vector_u_len : Number = (vector_p.length * Math.sin(rad_b)) / Math.sin(rad_g);
var vector_v_len : Number = (vector_p.length * Math.sin(rad_a)) / Math.sin(rad_g);
var factor_u : Number = vector_u_len / vector_up.length;
var factor_v : Number = vector_v_len / vector_right.length;

// Draw debug stuff...

// Select cell under mouse cursor
var cell : Cell = getCell(int(factor_u), int(factor_v));
if (m_selectedCell) m_selectedCell.setColor(Cell.COLOR_GREEN);
m_selectedCell = cell;
m_selectedCell.setColor(Cell.COLOR_RED);

}

 

Here’s it in action. Click on the cells to select them.

 

Click here to download example source.

Leave a Reply

Your email address will not be published. Required fields are marked *