Created
April 11, 2019 19:30
-
-
Save MAKIO135/1825fd83399f5e4df6f8b0d10399f465 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class HexGrid { | |
constructor(firstX, firstY, sizeX, sizeY, hexSize, type) { | |
// type can be either 'flat' or 'pointy' | |
type = type === 'flat' || type === 'pointy' ? type : 'flat' | |
this.width = sizeX | |
this.height = sizeY | |
let h = Math.sqrt(3) * hexSize | |
let w = 2 * hexSize | |
if(type === 'pointy') [w, h] = [h, w] // swap | |
console.log({w, h}) | |
this.hexPoints = this.getHexPoints(type, w, h) | |
const nbHexX = type === 'flat' ? | |
2 + (sizeX / (w * 3/4)) : | |
2 + (sizeX / (w * 1/2)) | |
const nbHexY = type === 'flat' ? | |
2 + (sizeY / (h * 1/2)) : | |
2 + (sizeY / (h * 3/4)) | |
console.log({nbHexX, nbHexY}) | |
this.centers = this.getCenters(firstX, firstY, nbHexX, nbHexY, w, h, type) | |
} | |
getHexPoints(type, w, h) { | |
if(type === 'flat') { | |
return [ | |
{ | |
x: w / 2, | |
y: 0 | |
}, | |
{ | |
x: w / 4, | |
y: h / 2 | |
}, | |
{ | |
x: -w / 4, | |
y: h / 2 | |
}, | |
{ | |
x: -w / 2, | |
y: 0 | |
}, | |
{ | |
x: -w / 4, | |
y: -h / 2 | |
}, | |
{ | |
x: w / 4, | |
y: -h / 2 | |
}, | |
] | |
} | |
else if(type === 'pointy') { | |
return [ | |
{ | |
x: 0, | |
y: -h / 2 | |
}, | |
{ | |
x: w / 2, | |
y: -h / 4 | |
}, | |
{ | |
x: w / 2, | |
y: h / 4 | |
}, | |
{ | |
x: 0, | |
y: h / 2 | |
}, | |
{ | |
x: -w / 2, | |
y: h / 4 | |
}, | |
{ | |
x: -w / 2, | |
y: -h / 4 | |
}, | |
] | |
} | |
} | |
getCenters(firstX, firstY, nx, ny, w, h, type) { | |
const centers = [] | |
if(type === 'flat') { | |
for(let i = 0; i < ny; i ++){ | |
for(let j = 0; j < nx; j ++){ | |
let x = firstX + (j * w * 3/2) + ((i % 2) * w * 3/4) | |
let y = firstY + (i * h * 1/2) | |
centers.push({x, y}) | |
} | |
} | |
} | |
else if(type === 'pointy') { | |
for(let i = 0; i < ny; i ++){ | |
for(let j = 0; j < nx; j ++){ | |
let x = firstX + (j * w) + ((i % 2) * w * 1/2) | |
let y = firstY + (i * h * 3/4) | |
centers.push({x, y}) | |
} | |
} | |
} | |
return centers | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment