If you build anything around Minecraft worlds, a map viewer, a Discord bot, a server plugin dashboard, you end up writing the same handful of coordinate conversions. They are simple, but two details trip people up: negative numbers and the difference between dividing and flooring. Here are the conversions in TypeScript with the edge cases handled.
Overworld and Nether
Horizontal distances in the Nether are scaled by 8. Y stays the same.
type XYZ = { x: number; y: number; z: number };
export const toNether = (p: XYZ): XYZ =>
({ x: Math.floor(p.x / 8), y: p.y, z: Math.floor(p.z / 8) });
export const toOverworld = (p: XYZ): XYZ =>
({ x: p.x * 8, y: p.y, z: p.z * 8 });
Why Math.floor and not Math.trunc or | 0? Truncation rounds towards zero, so -9 / 8 becomes -1 instead of -2. Block coordinates are integers that always round down, and getting this wrong puts portals one block off on the negative side of the world, which is exactly where people complain that their portal links "randomly".
Block to chunk
Chunks are 16 by 16 blocks. Again, floor, not truncate:
export const chunkOf = (x: number, z: number) =>
({ cx: Math.floor(x / 16), cz: Math.floor(z / 16) });
// or, for integers, an arithmetic shift does the same and handles negatives:
export const chunkOfInt = (x: number, z: number) => ({ cx: x >> 4, cz: z >> 4 });
The position inside the chunk is the remainder, kept positive:
export const inChunk = (x: number, z: number) =>
({ lx: ((x % 16) + 16) % 16, lz: ((z % 16) + 16) % 16 });
Chunk to region file
World saves group 32 by 32 chunks into region files named r.<rx>.<rz>.mca:
export const regionOf = (cx: number, cz: number) =>
({ rx: cx >> 5, rz: cz >> 5, file: `r.${cx >> 5}.${cz >> 5}.mca` });
This is handy when you want to prune or back up only the part of a world around a base.
Tests that catch the classic bugs
console.assert(toNether({ x: -9, y: 64, z: 7 }).x === -2);
console.assert(chunkOfInt(-1, 0).cx === -1);
console.assert(inChunk(-1, -17).lz === 15);
console.assert(regionOf(-1, 31).rx === -1 && regionOf(-1, 31).rz === 0);
Every assertion here fails with naive truncation, which is the point.
Do you need to write it at all?
For a quick lookup while playing, no. Minecraft Seed Map's coordinate converter does the Overworld/Nether conversion and shows chunk coordinates in the browser. The code above is for when the conversion has to live inside your own tool, where those two lines with Math.floor save a surprising number of bug reports.
Top comments (0)