I’ve got a basic follow script set up for a set of enemies. The script is supposed to make the enemy look at the player up to a certain distance and, when the player gets close enough, follow the player. The script sort of works, but for some reason, when I set the maximum follow distance to anything above 10, the enemies will run away from the player instead. If I somehow get the player to the with the 10 range of the enemy before they spawn they will follow as they are supposed to.
Here’s the entire enemy code:
public float MaxDistance = 10.0f;
public float MoveSpeed = 5.0f;
public float MinDistance = 0.0f;
public Transform Target;
public float LookAtDistance = 10.0f;
public float Distance;
public float Damping = 5.0f;
private Quaternion rotation;
public bool parenting = false;
private PlayerHealth_Test playerHealth;
private float nextDam;
//private Bank rolling;
public bool rolling = false;
public float DamDelay = 2.0f;
private Leech_Mother_AI_Test spawnCount;
private GameObject LeechMother;
void Start (){
Target = GameObject.FindGameObjectWithTag ("Player").transform;
playerHealth = Target.GetComponent<PlayerHealth_Test>();
parenting = false;
// rolling = Target.GetComponent<Bank>();
nextDam = Time.time + DamDelay;
GameObject spawner = GameObject.Find ("Leech_Mother");
spawnCount = spawner.GetComponent<Leech_Mother_AI_Test>();
}
void OnTriggerEnter(Collider Player)
{
transform.parent = GameObject.FindGameObjectWithTag("Player").transform;
parenting = true;
}
void Update () {
Distance = Vector3.Distance (Target.position + Target.transform.forward, transform.position);
if (Distance < LookAtDistance)
{
LookAt();
}
if (Distance > MinDistance && Distance < MaxDistance && parenting == false)
{
follow ();
}
if (rolling == true)
{
parenting = false;
GameObject.Destroy(this.gameObject);
spawnCount.SpawnDown(1f);
}
if (parenting == true && nextDam <= Time.time)
{
nextDam = Time.time + DamDelay;
playerHealth.CurrentHealth -= 1.0f;
}
if (parenting == true && playerHealth.CurrentHealth <= 0)
{
parenting = false;
}
}
void LookAt(){
rotation = Quaternion.LookRotation (Target.localPosition - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * Damping);
}
void follow(){
transform.Translate(Vector3.forward * MoveSpeed * Time.deltaTime);
}
}
Wow, you wrote quite a code to do this... Just a small tought before I think of an answer, you know that the transform have a lookAt function? Plus I'm not sure if your distance calculation is correct.
– gajdot