We have an array of hexagons that a line, from the center of a starting hexagon goes to the center to a target hexagon (this works well).
The start hex and target hex centers are:
Var p1 As Point = GetCenter(from)
Var p2 As Point = GetCenter(tohex)
For each hexagon in the array we get its center and call GetHexagonEnteringSide
to get the side of the hexagons from where the line enters to the hex.
Var hexagon As Point = GetCenter(hex)
Public Function GetHexagonEnteringSide(p1 As Point, p2 As Point, hexagon As Point) As Integer
' Define Pi
Const Pi = 3.14159265358979323846264338327950
' Calculate the vector representing the line
Var lineVector As New Point(p2.X - p1.X, p2.Y - p1.Y)
' Calculate the vector representing the hexagon center to the starting point
Var hexagonToStartVector As New Point(p1.X - hexagon.X, p1.Y - hexagon.Y)
' Calculate the angle between the line vector and the hexagonToStartVector
Var angle As Double = Atan2(lineVector.Y, lineVector.X) - Atan2(hexagonToStartVector.Y, hexagonToStartVector.X)
' Normalize the angle to be within [0, 2 * Pi)
If angle < 0 Then angle = angle + 2 * Pi
' Determine the hexagon entering side based on the normalized angle
Var enteringSide As Integer = 1 + round(angle / (Pi / 3)) Mod 6
' Return the entering side
Return enteringSide
End Function
But, something is not working and I can’t find what is it. The resulting entering side is not correct always and I do not have enough skills on Vectors, angles, etc.
Can anyone give some light ?.