I'm making a 2D game with two spaceships flying around and shooting at each other. One is controlled by the player, the other by the AI.
Currently, I have the AI always try to get inside a certain radius from the player. When it is inside that radius, it stops moving. This works, but I have one problem with this. I'll present the problem after describing the implementation:
Each frame, the AI checks it's distance from the player. If the distance is larger than a certain number (the radius), the AI moves in the direction of the player. If the distance is smaller or equal to that number (aka the AI's spaceship is inside the given radius from the player's ship), the AI stops moving.
This works fine, except for one problem:
When I stay in place and let the AI's ship reach the radius, it works. The AI moves in my direction, and stops the moment it got inside the radius. The movement is smooth.
The problem occurs when - after the AI had reached the radius and stopped - I start moving my ship. The AI senses that it's no longer inside the radius, and starts following me, but in a very fragmented fashion.
It moves for a few pixels in my direction, stops, then moves for a few pixels, than stops.
(These 'few pixels' are the 'moving step' both ships take while moving, every frame. The amount of pixels in each step is constant).
I figured out the reason for this problem:
When both ships are in place next to each other (aka the AI is inside the radius so it doesn't need to move), and then the player's ship starts moving, the AI senses right away that it is now outside of the radius. It moves immediately one step in the player's direction.
The next frame, the AI senses that it's once again inside the radius. So it stops.
But the player is in motion. So the frame after that, again the AI senses it's outside the radius, and moves.
This creates very fragmented motion. The AI moves a step, stops, moves another step, stops.
I know what causes this problem, but not how to fix it.
Any suggestions as to how to fix this problem? What could cause this in the design I described?