I'm working on coding enemy ai for a star fox-esqe shooter and I need the enemy to approach the player, stay a certain distance away and stay in front of them until destroyed. I can get the enemy to approach the player and I can get the enemy to stay a certain distance from the player but I'm not sure how to get the enemy to actually stay in front of the player. For a bit of extra information, the player makes a number of sharp turns and the like throughout the level. Also, as a stand in I tried simply causing the enemy to parent to the player within a certain radius but that causes clipping issues with buildings and the ground.
public class EnemyCar: MonoBehaviour
{
public float safeDistance = 20f; // How close the enemy can get to the player
// ...
// Update is called once per frame
void Update()
{
transform.LookAt(player.transform);
Vector3 targertLocation = player.transform.position - transform.position;
float distance = targertLocation.magnitude;
// Decrease our speed as we get closer
rb.AddRelativeForce(Vector3.forward * Mathf.Clamp((distance - 30) / 50, 0f, 1f) * thrust);
}
}