A Hex on your Grid - Distance between plots

whoward69

DLL Minion
Joined
May 30, 2011
Messages
8,725
Location
Near Portsmouth, UK
As I could find no reference to calculating the distance between two tiles on a hex grid, I though I'd share the results of my "JFGI"

Code:
-- Calculate the distance between two plots
--
-- See http://www-cs-students.stanford.edu/~amitp/Articles/HexLOS.html
-- Also http://keekerdc.com/2011/03/hexagon-grids-coordinate-systems-and-distance-calculations/
--
function distanceBetween(pPlot1, pPlot2)
  local mapX, mapY = Map.GetGridSize()

  -- Need to work on a hex based grid
  local hex1 = PlotToHex(pPlot1)
  local hex2 = PlotToHex(pPlot2)

  -- Calculate the distance between the x and z co-ordinate pairs
  -- allowing for the East-West wrap, (ie shortest route may be by going backwards!)
  local deltaX = math.min(math.abs(hex2.x - hex1.x), mapX - math.abs(hex2.x - hex1.x))
  local deltaZ = math.min(math.abs(hex2.z - hex1.z), mapX - math.abs(hex2.z - hex1.z))

  -- Calculate the distance between the y co-ordinates
  -- there is no North-South wrap, so this is easy
  local deltaY = math.abs(hex2.y - hex1.y)

  -- Calculate the distance between the plots
  local distance = math.max(deltaX, deltaY, deltaZ)

  -- Allow for both end points in the distance calculation
  return distance + 1
end

function PlotToHex(pPlot)
  local hex = ToHexFromGrid(Vector2(pPlot:GetX(), pPlot:GetY()))

  -- X + y + z = 0, hence z = -(x+y)
  hex.z = -(hex.x + hex.y)

  return hex
end

Hope this helps someone else

W
 
I've not tested any, but is it different than Map.PlotDistance() ?
 
I've not tested any, but is it different than Map.PlotDistance() ?

Dunno. Documentation like

"MaxPlotDistance(?) -> ?
PlotDistance(?) -> ?"

is worse than useless.

If you want a documented and tested method, use mine, if you like "crystal ball gazing" (and I don't) try those two ;)
 
Yes, Map.PlotDistance works just fine. If I remember right, it's
Code:
dist = Map.PlotDistance(x1,y1,x2,y2)

While it's not documented in the wiki very well, there are several functions in the vanilla game's UI that use this function, so it's easy to find an example or two with a quick search through the Steam directory.

I'll double-check the above when I get home; I use this function in a couple of my scripts, and it works just fine.
 
I'll double-check the above when I get home; I use this function in a couple of my scripts, and it works just fine.

Okay, I confirmed the syntax I gave earlier. For reference, this function is used in quite a few places in the UI code. The first place I saw it was in InGame/Bombardment.lua, which draws a ring at the ranged unit's maximum range. Also, the popup when you first meet a city-state, for instance, uses it to determine which resources are listed as "nearby". So it's easy to confirm what I said.
 
Back
Top Bottom