Hi,
I'm using the following code to draw a line between 2 hexes in a hexagonal tilemap.
In some cases, the calculated line has the same hex twice instead of the correct hex as seen in the screenshot i'll add below.
func oddq_to_cube(hex) -> Vector3i:
var q = hex.x
var r = hex.y - (hex.x - (hex.x&1)) / 2
var z = -q - r
var cube = Vector3i(q,r,z)
return cube
func cube_to_oddq(hex) -> Vector2i:
var q = hex.x
var r = hex.y + (hex.x - (hex.x&1)) / 2
var cube = Vector2i(q,r)
return cube
func cube_distance(a,b):
var x = a.x - b.x
var y = a.y - b.y
var z = a.z - b.z
var cubesubtract = int((abs(x) + abs(y) + abs(z))/2)
return cubesubtract
func Lerp(a, b, t): # for floats
var Lerp = a * (1-t) + b * t
return Lerp
func cube_lerp(a,b,t):
var cubeA = Lerp(a.x,b.x,t)
var cubeB = Lerp(a.y,b.y,t)
var cubeC = Lerp(a.z,b.z,t)
var Cube_lerp = Vector3i(cubeA,cubeB,cubeC)
return Cube_lerp
func cube_round(frac):
var x = round(frac.x)
var y = round(frac.y)
var z = round(frac.z)
var x_diff = abs(x - frac.x)
var y_diff = abs(y - frac.y)
var z_diff = abs(z - frac.z)
if x_diff > y_diff and x_diff > z_diff:
x = -y -z
elif y_diff > z_diff:
y = -x -z
else:
z = -x -y
var round_cube = Vector3i(x,y,z)
return round_cube
func Line_draw(Lstart,Lend):
var N = cube_distance(Lstart,Lend)
var a_nudge = Vector3i(Lstart.x + 1e-6,Lstart.y + 1e-6,Lstart.z - 2e-6)
var b_nudge = Vector3i(Lend.x + 1e-6,Lend.y + 1e-6,Lend.z - 2e-6)
var results = []
var step = 1.0/max(N,1)
for i in range(N + 1):
results.append(cube_round(cube_lerp(a_nudge,b_nudge,step*i)))
return results
var cubepath = Line_draw(startcube,endcube)
for i in cubepath.size():
var id = cube_to_oddq(cubepath[i])
print(id)
path.set_cell(0, id, 1, Vector2(0, 0))
print("end")
(13, 15)
(13, 15)
(14, 17)
(14, 17)
(15, 18)
(15, 18)
(16, 20)
end
is what is printed.
I know the code is messy, i'm new to programming and most of my code is frankensteined from tutorials.