How to make a simple AI escape script?

I want to make a 2D game. I made scripts for controlling player and simple enemy movement.
The enemies should flee from player. I check if player is near to enemy by `Vector2.Distance`
and then make enemy’s input equal to player’s `Input.GetAxis` . But it doesn’t work correctly and I know why.
How to make enemy escape from player?

You could add a collider to the enemy. Use a circle Collider and make it way bigger than your enemy is, than set it “is Trigger”. If the player enters the Trigger then let the enemy run in the opposite direction. Its like a big bubble around the enemy and if something enters the bubble the enemy will run away. If the Player leavs the trigger it should stop the enemy from running away instantly.

This might not be the best solution but its a simple one in my opinion.

Here’s what i did;

``````Vector3 playerPos;
Vector3 ThisPos;
GameObject Player;

void Start ()
{
Player = GameObject.FindGameObjectWithTag("Player");
}

void Update ()
{
if (Player != null)
{
playerPos = Player.transform.position;
}

thisPos = transform.position;

Collider2D[] collis = Physics2D.OverlapCircleAll(transform.position, minRange); // this creates a range so that when the player enters it the ai will tell it to move away
foreach (Collider2D colli in collis){
if (colli && colli.tag == "Player")
{ // if object has the right tag...
transform.position = Vector2.Lerp(thisPos, -playerPos, Time.deltaTime * Speed); // this tells it to move toward the inverse of the players position.
}
}
}
``````

Hope this helps. make sure that you tag your player gameobject as “Player” otherwise it won’t do anything.(Speed is the rate at which you want it to move its a Float value so just set to anything to begin with, you can fine tune it later.