xonecas.ioDon't click! Sean Caetano Martin Sign in
tiny-adventure / web / js / hex.js 27 lines969 bytes Raw
1import * as THREE from '../vendor/three.module.js';
2
3export const HEX = 0.62;
4
5export function hexToWorld(col, row, target = new THREE.Vector3()) {
6  return target.set(HEX * Math.sqrt(3) * (col + (row & 1) / 2), 0, HEX * 1.5 * row);
7}
8
9const toAxial = (col, row) => [col - (row - (row & 1)) / 2, row];
10const fromAxial = (q, r) => [q + (r - (r & 1)) / 2, r];
11
12export function worldToHex(x, z) {
13  const q = ((x * Math.sqrt(3)) / 3 - z / 3) / HEX;
14  const r = (z * 2) / 3 / HEX;
15  let [rq, rr] = [Math.round(q), Math.round(r)];
16  const rs = Math.round(-q - r);
17  const [dq, dr, ds] = [Math.abs(rq - q), Math.abs(rr - r), Math.abs(rs + q + r)];
18  if (dq > dr && dq > ds) rq = -rr - rs;
19  else if (dr > ds) rr = -rq - rs;
20  return fromAxial(rq, rr);
21}
22
23export function hexDistance(col1, row1, col2, row2) {
24  const [q1, r1] = toAxial(col1, row1);
25  const [q2, r2] = toAxial(col2, row2);
26  return (Math.abs(q1 - q2) + Math.abs(r1 - r2) + Math.abs(q1 + r1 - q2 - r2)) / 2;
27}