I am working on a game map, that is made up of a hex grid. Currently I am saving the center points of each element to a list when they are generated. I want to have the tile the current mouse is over, to be highlighted. I have it working by taking the mouse position, and using the distance formula, and loop through each element to find the closest element to the mouse.
CENTER LIST is a list of centerpoints for each hex tile.
def get_distance(x1, y1, x2, y2):
dist = sqrt((x2 - x1)**2 + (y2 - y1)**2)
return dist
def find_nearest_hex(pos):
index = 0
min_val = 10000
for i in range(len(CENTER_LIST)):
x,y= CENTER_LIST[i]
if get_distance(pos[0], pos[1], x, y) < min_val:
min_val=get_distance(pos[0], pos[1], x, y)
index = i
return index
If anyone has ideas on how to do this more in a more efficient way I would love to hear them.