/isometric.ts Secret
Last active
April 14, 2025 12:20
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// These are the four numbers that define the transform, i hat and j hat | |
const i_x = 1; | |
const i_y = 0.5; | |
const j_x = -1; | |
const j_y = 0.5; | |
// Sprite size | |
const w = 32; | |
const h = 32; | |
function to_screen_coordinate(tile: Vector2) { | |
// Without accounting for sprite size | |
return { | |
x: tile.x * i_x + tile.y * j_x, | |
y: tile.x * i_y + tile.y * j_y, | |
} | |
// Accounting for sprite size | |
return { | |
x: tile.x * i_x * 0.5 * w + tile.y * j_x * 0.5 * w, | |
y: tile.x * i_y * 0.5 * h + tile.y * j_y * 0.5 * h, | |
} | |
} | |
// Going from screen coordinate to grid coordinate | |
function invert_matrix(a, b, c, d) { | |
// Determinant | |
const det = (1 / (a * d - b * c)); | |
return { | |
a: det * d, | |
b: det * -b, | |
c: det * -c, | |
d: det * a, | |
} | |
} | |
function to_grid_coordinate(screen: Vector2) { | |
const a = i_x * 0.5 * w; | |
const b = j_x * 0.5 * w; | |
const c = i_y * 0.5 * h; | |
const d = j_y * 0.5 * h; | |
const inv = invert_matrix(a, b, c, d); | |
return { | |
x: screen.x * inv.a + screen.y * inv.b, | |
y: screen.x * inv.c + screen.y * inv.d, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@jordwest Thanks for the snippet, It came in handy for a little isometric grid experiment I was trying