I need to attach text labels to objects that are spread randomly across the screen and keep moving.
The default and ideal position for a label is on the right side of the object it refers to. I need a way to dynamically rearrange (or possibly merge) the labels so that they never overlap each other or other objects.
They should still be as close to the objects as possible and should not, provided that the objects themselves move smoothly, show any suddent jerky movement.
I have no idea how to do it, is there an algorithm for something like this?
I solved this using pretty much brute force
and do this in a cycle several times because objects grow when they swallow other objects, so the collision check has to be done again (new overlaps may appear mid-cycle). Never hit more than 3 cycles though, with the number of objects I’m working with.
The should_swallow() function determines if it’s better to swallow an objects or get swallowed by it, based on size, position and what happened in previous frames to prevent flicker.