# Finding cells within range on a hexagonal grid

I'm looking for a way to get the cells based on a N range. But no luck.

I'm converting Row Column offset to Cube Coordinate system QR -> XYZ

$range = 1; for ($dx = -$range;$dx <= $range;$dx++)
{
for ($dy = max(-$range, -$dx -$range); $dy <= min($range, -$dx +$range); $dy++) {$dz = -$dx-$dy;
$points =$hexagon->cube_to_oddq(array($dx,$dy,$dz));$x = $hexagon->ver +$points * $hexagon->size * 1.5;$y = $hexagon->height +$points * $hexagon->height + ( ($points%2) * ( $hexagon->height / 2 ) );$points = $hexagon->drawHex($x,$y, true);$pointss = array();
foreach($points as$p) {
$pointss[] =$p;
$pointss[] =$p;
}
imagefilledpolygon ( $png_image ,$pointss , 6 , $black ); } }  Result: Inside every hex cell (First line is QR coordinate) (Second line is XYZ converted coordinate) Any advice what I'm doing wrong? Update: As requested, the Oddq (Q,R) to Cube conversion XYZ $i = $hex = ROW$j = $hex = COLUMN public function oddq_to_cube($hex){
$hex =$hex;
$x =$hex;
$z =$hex - ($hex - ($hex&1)) / 2;
$y = -$x-$z; return array($x, $y,$z);
}
$curr_cube =$hexagon->oddq_to_cube(array($i,$j));

• Your conversion from offset columns to cube coordinates is not correct. Reading along a line of neighbouring hexes, we should see the same cube coordinate offset to each successive neighbour. eg. if going down from (0, 0, 0) took me to (-1, 0, 1), then a taking another step down should take me to (-2, 0, 2), then (-3, 0, 3) etc. But your xyz coordinate offsets change as we read along a line. We'd need to see the code for your conversion to diagnose what's going wrong inside it. Aug 2, 2017 at 9:39
• Dear @DMGregory, updated the question. Aug 2, 2017 at 14:48
• As posed, the question still doesn't have enough information to answer the question. For example, the coordinates in the screenshot do not actually match the dx, dy, dz code in the question, and you posted the code for oddq_to_cube while the original question only used cube_to_oddq. I'm also confused whether your variables $x and $y are in (X, Y, Z) as cubical coordinates or x, y as screen coordinates, as well as the intended behavior or drawHex and imageFilledPolygon. Aug 2, 2017 at 18:23
• Let me upload the full code. Aug 2, 2017 at 22:27
• @Jimmy pastebin.com/0EvVm011 and the class is this pastebin.com/P6STfgbL Aug 2, 2017 at 22:32

for ($dx = -$range; $dx <=$range; $dx++) { for ($dy = max(-$range, -$dx - $range);$dy <= min($range, -$dx + $range);$dy++)
$x = 96 +$hexagon->ver + $hexagon->size * 1.5 *$dx;
$y = 54.6 +$hexagon->height + $hexagon->height *$dy + $hexagon->height/2 *$dx;
$points =$hexagon->drawHex($x,$y, true);