I've been searching hard to solve this one -- so I really must ask for help.
I've created a CSS based game map that overlays DIV's in the shape of Hexagon Tiles (like table top games). I'm trying to find which tiles are adjacent to the current active tile.
I've been able to generate the ID's of the map sequentially from top left to bottom right and assign coordinates to each of the tiles. From there I used the Pythagorean Theorem to calculate distance between the 2 X&Y Coords (this took me a while to figure out). Things are actually very close, but the problem is that because a hex tile map is essentially "staggered" (e.g. it's not a square grid and two adjacent tiles are not on the same exact horizontal line), when I calculate distance, a few tiles that are actually 2 steps away, math out to closer than a tile just adjacent.
I've put up a demo of what I built so you can see exactly what I'm talking about.
http://www.pitashi.com/map/index.php
If you click on any tile, it will refresh the page and put a flag on your "current location". Then each of the tiles displays the coordinates and the calculated distance from the current location. If you click around, you'll see that many of the tiles that don't border the current location are closer in distance.
CODE:
// load the map DIV tags (90 tiles)
if (isset($_GET['x'])) {
$gl_map_x = $_GET['x'];
} else $gl_map_x = 0;
if (isset($_GET['y'])) {
$gl_map_y = $_GET['y'];
} else $gl_map_y = 0;
if (isset($_GET['mapid'])) {
$gl_map_id = $_GET['mapid'];
} else $gl_map_id = 42;
$i = 1;
$x = 0;
$y = 0;
while ($i <= 90) {
echo "<div class='hexagon hexagon" . $i . "' onclick=\"window.location=('index.php?mapid=". $i . "&x=" . $x . "&y=" . $y . "')\"><div class='hexagon-in1'>";
echo "<div class='hexagon-in2'>";
if ($i == $gl_map_id) {
echo "<img class='hexstar" . $i . "' src='images/map_star1.png' />";
}
$distance = round(sqrt(pow($gl_map_x - $x, 2) + pow($gl_map_y - $y, 2)), 2);
echo "<div style='color:#ffffff; padding-left:48px; padding-top:30px;'>" . $x . ", " . $y . "<br />" . $distance . "</div>";
//echo "<div style='color:#ffffff; font-weight:bold; padding-left:48px; padding-top:30px;'>" . $distance . "</div>";
//echo "<div style='color:#ffffff; padding-left:48px; padding-top:30px;'>" . $i . "</div>";
echo "</div></div></div>";
$i++;
$x = $x + 63;
if ($x > 756) {
$x = 63;
$y = $y + 54;
} elseif ($y == 432) {
$x = $x + 63;
}
}
?>
I know there must be some additional math I need to use to compensate for the staggering of the tiles, but I'm way out of my pay grade on this one. But this functionality is essential to my little RPG game.
Any suggestions?