Skip to content

Instantly share code, notes, and snippets.

@rjmoggach
Created August 17, 2011 04:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjmoggach/1150829 to your computer and use it in GitHub Desktop.
Save rjmoggach/1150829 to your computer and use it in GitHub Desktop.
Pixel 2 Hex Coordinate hack
// cellRadius is the distance from center to vertex or length of an edge
// longSpan is the long side of the triangle
// shortSpan is short side
float[][] XM = new float[][] { { 1 / (2*longSpan), -1 / cellRadius }, { 1 / longSpan, 0 } };
float[][] YM = new float[][] { { 1 / (2*longSpan), 1 / cellRadius }, { -1 / (2*longSpan), 1 / cellRadius } };
HVector pixel2hex(PVector pv) {
int n;
PVector mj = floorDot(pv, matrixXM);
int j = floor((mj.x+mj.y+2)/3);
PVector mk = floorDot(pv, matrixYM);
int k = floor((mk.x+mk.y+2)/3);
return new HVector(j,k);
}
PVector hex2pixel(HVector hv) {
float x, y;
x = hv.j * (2*longSpan) + hv.k*longSpan;
y = hv.k * cellSide;
return new PVector(x,y,0);
}
PVector floorDot(PVector v, float[][] mtx) {
float j = floor(mtx[0][0]*v.x + mtx[0][1]*v.y);
float k = floor(mtx[1][0]*v.x + mtx[1][1]*v.y);
return new PVector(j,k,0);
}
/* HVector is a class derived entirely from Processing PVector but
uses integers instead of floats */
@dbatten5
Copy link

Hi, when you say

longSpan is the long side of the triangle

to which triangle do you refer? I really like this solution but am a little bit confused on how to go about calculating longSpan, cellRadius and shortSpan. It also appears that shortSpan isn't used in the code?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment