Framework Merchant Empires :: Tutorial :: Hexagonal Navigation 1


Assuming that Hex navigation is your goal (meaning you'll scrap the rest of my work like grease from ground beef intended for spaghetti), you may find this particular tutorial quite helpful. I am going to show you how to handle hex navigation using components from my project.

This article is intended for advanced php developers and will not be suitable for guys who have never coded a game before. No support will be given for this article. If you are new to the whole game coding experience, please start out a bit lower on the ladder. You will not find this tutorial easy, nor will you have anything to show for it but a huge array of numbers.

By the end of this tutorial you will have a list of sector numbers in coordinate pairs, including some extra information like ring number and distance from both origins. The required input is the radius of the hexagonal galaxy (ring count) and a coordinate pair. A coordinate pair in the cartesian system consists of X and Y (typically). Polar systems use something like A and D (angle and distance). A hex system could use either of these, but I prefer T and G. These describe distances from the origin 0,0 either up and right (T) or up and left (G).

Take a look a this screenshot for an idea of what I am talking about. Take careful note of the orientation of the hexagons (the tops and bottoms are flat and parallel). The orientation and positioning is how my hex engine works, so pay attention!

There are two origins to consider. The first origin, or prime origin, is at the coordinate 0,0 (just like in a cartesian or polar system). The second origin is the center of the "window" you are using to center the hex grid on. In the screenshot link above, the secondary origin is 0,-4. Notice the dark grey numbers on the left side of the sectors. These numbers represent how far from the primary origin a player is, and therefore the orbital ring

You will need to know how many rings you want. There is almost no performance implications of having a system with 10,000 rings, except for the sector numbers are 5 digits long, so you use 5 times as much memory than a 6 ring system. Either way the footprint is small, like 400 bytes per map. The algorithm does not load the entire structure. A typical viewing area (like in the screenshot) is 19 sectors, but because of limitations in the CPU transistor, 25 sectors are loaded, and 12 of them are pruned out.

When storing maps, I store the radius and the side count (6). When storing positions, I store the map ID number and the t,g coordinate pair.

Are you ready to get started? You will need a fresh copy of the framework package, which can be downloaded from this link at the Sourceforge site. If you are not going to use the whole package in your application, you will have to steal the file obj.type.hex.php from the objects folder. Open up this file in your php editor.

Once you have caught up, move on to the next page.