Enemy Detection
Hi everyone, I'm very new to making games and coding so i started watching some tutorials online. I'm pretty deep in making my game and now I'm working on the enemies (flying), but the way my script has it is the enemy just takes your position(wherever you may be) and moves to it(explodes on contact with you). And there's nothing wrong with that except that this is a side scrolling game and i don't want the enemies to move to me until i am a certain distance from them. Is there a way i can do this? I have 3 enemy scripts what should i change to get the effect that i need? I uploaded the scripts on my post on the forum you can find them here
Answer by lawrence-parry · Sep 17, 2016 at 11:58 PM
Ok, so you need to test the distance to the player before moving?
if(Vecotr3.Distance(player.transform.position,transform.position)<desiredDistance){
//move towards player
}
You will need to assign 'player' either in the inspector or by using GameObject.Find() and set 'desiredDistance' to whatever you want the distance to be.
However this will mean that if the player goes within that distance and then goes beyond that distance again the enemy wont keep following. This may be what you want be if you want them to keep following the player make a bool to that represents whether the player has been spotted. Here I have called it isSpotted.
if(!isSpotted){
if(Vecotr3.Distance(player.transform.position,transform.position)<desiredDistance){
isSpotted = true;
}
}else{
//move towards player
}
If you do this then once the player goes within the distance the enemy will keep following them even if they go beyond that distance again.
I don't know if this is what you were after but I hope it helps :)