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?
2 Answers
2You 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.
Thank you! I did something like that, with collider, but how to make enemy run in the opposite direction? How to check it?
– kopkinhoThank you, that works for me, but I used OnTriggerStay2D. But it's not smooth movement. function OnTriggerStay2D() { if (player.position.x < transform.position.x) { transform.position.x += Time.deltaTime * 10; } else transform.position.x -= Time.deltaTime * 10; if (player.position.y < transform.position.y) { transform.position.y += Time.deltaTime * 10; } else transform.position.y -= Time.deltaTime * 10; }
I am glad I could help a bit. I dont know how to get the movement more smooth, but I am sure there is a way to do it :D
– TheRefoHHere’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.
Hello 7Why, I did trying to use your code but the Inverse direction doesn't work very well thou. It's just keep moving to the left. If you are still around please guide me around. Peaace ^^
– BahamutZeRo
We need to see your code and possibly a more detailed description of the desired behavior.
– robertbu