Making an enemy stay in front of the player no matter how they move.

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.

I’m currently digging through tutorials but if anyone can tell me what type of code I would need/how to use said code (I was told Raycasting might work and that’s what I’m trying to look up now) or simply point me in the direction of specific tutorial that would be a great help.

C# would be preferred, I’m not that great a Java.

You need to decide what you really want to happen under what conditions and think of the consequences of it. If you have the enemy try to stay in front of the player how will it look? What if the player faces a wall, if the player turns around suddenly, etc. Anyway…

To keep the enemy away from the player:

  • Put a collider on the enemy and mark it as a trigger
  • Script the enemy to move away from the player when the player is inside the trigger area and you’re not already moving away. If you want to go directly away, use the vector of the player’s position - the enemy’s position.

To keep the enemy in front of the player:

  • Determine the angle of facing that you want the enemy to try to be within.
  • The player’s transform.forward is its facing (unless you’ve done something strange).
  • The enemy’s position - the player’s position describes a vector between them.
  • Explore the meaning of dot product.
  • Convert the acceptable angle for your enemy to be within to a dot product result.
  • If the enemy isn’t within this range, move the enemy to a position in front of the player.
  • A position in front of the player is the player’s position + tranform.forward * distance.