Scripting Helpers is winding down operations and is now read-only. More info→
Log in to vote

Rounding to nearest Hex's Center? [closed]

Asked by
adark 5487 Badge of Merit Moderation Voter Community Moderator
9 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 = + .5)/6.062)*6.062, math.floor(pos.Y) + .5, math.floor((pos.Z + .5)/7)*7) +, 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).

Locked by adark

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

Why was this question closed?

1 answer

Log in to vote
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 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.