2

# Rounding to nearest Hex's Center? [closed]

8 years ago

Given a Hexagon-shaped field (in the Workspace), where every possible x/z coordinate is easily calculable from the internal mapping, as well as from the actual Hexs, what is the best way to round the Mouse's Hit position to the nearest Hex's Center?

This is my current code:

local pos = playerMouse.Hit.p
pos = Vector3.new(math.floor((pos.X + .5)/6.062)*6.062, math.floor(pos.Y) + .5, math.floor((pos.Z + .5)/7)*7) + Vector3.new(0, 0, (math.floor((pos.X + .5)/6.062)%2 == 0 and 0 or 3.5))


The problem with it, (ignoring the broken height for right now) is that this translates to this in how it rounds. The red mark is the Player's Mouse.Hit.p. My code will round that to the Hex that is in the majority of that blue box, rather than the Hex it is actually in.

I would just base the position on the Hex being 'hit', but this has to support placing tiles where no Hexes exist (yet).

This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.

2
BlueTaslem 18071
8 years ago

I have been working at the math for a more elegant solution and haven't come up with one yet.

However, here's a not-so-elegant solution that will at least give you accuracy. Hexagon maps are Voronoi diagrams which means there is a straighforward way to determine which cell a point belongs in:

A point belongs to the cell with the closest center to it.

Start with your approximation, then iterate over the adjacent locations (x±2, y±2). Find the cell with the minimum distance to the point, and that is the cell that the point is in.

Are you aware the exact value of 6.06... is just 7 sqrt(3) / 2 (or 7cos(pi/6))? It probably is a good idea to use the exact value rather than the approximation.