Auto targeting closest game objects for ship guns (SOLVED)

Hi,
I just started Defold today. I am porting a game that I have made from Game Maker to Defold.

The main character of the game is a ship made of a number of segments. These can be destroyed individually (I have made these as game objects segment01…segment20 and they share a common script called segment).

I am currently using a collection to represent a ship design (for example, “interceptor”) as a whole bunch of nested segments.

I have a game object that I use for adding turrets as well, and I do this by making the turrets children of the segments that they are on. This is nice because their position and rotation is relative. These turrets are automatic and will do as much damage as possible if there are any things in range to destroy.

Basically, if there is an enemy ship nearby (these are made of individual segments as well, preferably the same kinds as the friendly segments so I don’t need to make them all over again), I want to find which game object corresponds to the closest enemy ship segment. This is so that I know what direction to shoot the projectiles.

Note I can’t just grab a top level /enemy or something like that, because there will be multiple enemies, and the closest segment could belong to any enemy.

What’s the best pattern to use for this?

I’m not sure if this is the best, or most performant way, but I just made all my segment objects have collision objects and then I made a trigger object with a massive sphere mask on my turret. It receives messages when segments come into/leave range this way.

An issue that I have not been able to solve - when I spawn ships on top of each other, they don’t detect enemies in range until they move. Then, it will receive the proper notification.

Edit:
That is, unless I put this workaround in init …

self.position = self.position

This is a great solution to the problem and I doubt you’ll run into performance issues!