- Home /
enemy doesn't follow the player
I'm using a simple enemy ai that makes the enemy follow the player, I am wanting to spawn my enemies one after the other which I have done, but for some reason the enemy only follows the player if both the enemy and the player are in the scene, in other words when I asiign the player as the target in the assets folder when both prefabs are in the assets folder the enemy only moves to the players start potition, is there anyway I can fix this script to accomindate my enemy spawners
var Player : Transform; var MoveSpeed = 4; var MaxDist = 10; var MinDist = 5;
function Start () {
}
function Update () { transform.LookAt(Player);
if(Vector3.Distance(transform.position,Player.position) >= MinDist){
transform.position += transform.forward*MoveSpeed*Time.deltaTime;
if(Vector3.Distance(transform.position,Player.position) <= MaxDist)
{
//Here Call any function U want Like Shoot at here or something
}
}
}
Answer by AshwinTheGammer · Sep 26, 2017 at 05:24 AM
try this script
var Player : Transform;
var MoveSpeed = 4;
var MaxDist = 10;
var MinDist = 5;
function Start(){
target = GameObject.FindWithTag("Player").transform;
}
function Update () {
transform.LookAt(Player);
if(Vector3.Distance(transform.position,Player.position) >= MinDist){
transform.position += transform.forward*MoveSpeed*Time.deltaTime;
if(Vector3.Distance(transform.position,Player.position) <= MaxDist)
{
//Here Call any function U want Like Shoot at here or something
}
}
Answer by Timo326 · Sep 26, 2017 at 08:13 AM
If you assign the player as a prefab to your script, the target is only the position of the prefab. And the prefab's position does not change when your gameobject changes position. You should assign the transform of the gameobject to "target", not of the prefab. If you don't have the player created at start, you can find the target with
target = GameObject.FindWithTag("Player").transform;
if you have tagged it as "Player".
yes it works perfectly, jist had to tweak the variable names but other than that it work perfectly, thanks
Your answer
Follow this Question
Related Questions
Help with Enemy AI 1 Answer
Deal damage on collision 2 Answers
2D sidescroller ranged character shooting problem. 0 Answers
Enemy Spaceship Movement AI Curve Movement Need help Please 0 Answers