You may want to split your movement method up into two smaller methods.
The first can check for defensive movement conditions (when I need to run).
The second can check for offensive movement (getting into best position to attack from)
Let's Ask Questions About Retreating
Am I damaged?
Do I have a way to effectively heal this unit if I make it run away?
Am I in danger?
How many allies are near me?
How many enemies?
How strong are they?
How do I run away?
Move away from the nearest enemy?
Move away from the enemy base ship?
Move toward my base ship?
Am I too clumped up with my allies?
Does my enemy have weapons which deal area-of-effect damage?
How much do I need to spread out?
Hint: You can get a weapon's area of effect by using the getRadius() weapon.
A Tip Retreating
Be careful that your units don't end up bobbing back and forth into and out of combat. If you simply say "retreat when an enemy is near me and I have low health" you'll keep trying to get near the specified radius.
Instead, make sure you're retreating with a purpose. This could mean:
Set a boolean to tag your unit in retreatMode. Always run if in retreatMode. When certain conditions are met, set retreatMode to false.
Set an integer to start a retreatTimer. Always run if retreatTimer is greater than 0. Decrease retreatTimer every frame.
When your units are in danger, you can always have them retreat. Just make sure you have a plan about what they'll do next.
If your units have nearby enemies OR you want to attack because you have a stronger fleet, you may want to engage in offensive movement.
As long as your units didn't already retreat this frame you can reposition to get closer to better targets.
You likely wrote some helpers in the attack() method to find the best target in a radius. Consider reusing that method but with a larger radius. If a unit is outside of your range but a good target, you can move toward that unit.
Kite vs. Charge
Consider your range relative to your opponent. If they have MORE range, you may want to just charge them by getting as close as possible. If they have LESS range, you may want to kite them by staying at a distance.
When your enemy is using a long range weapon, you want to get a close as possible to them!
Every weapon has a minimum range, so you can potentially get close enough that they cannot fire on you.
When you're not actively fighting and don't intend to attack, you can always have units gather at some other location.
This might mean moving toward a specific point on the map, or moving to protect your Gatherers and Miners.