There are times when we want an AI-controlled NPC character to move away from another character, rather than go toward it. For example, an enemy with very low health might run away, and so gain time to regain its health before fighting again. Or, a wild animal might flee from any other character moving near it.
To instruct our NavMeshAgent component to flee from the player's location, we need to replace the ArrowNPCMovement C# script class with the following:
using UnityEngine;
using UnityEngine.AI;
public class ArrowNPCMovement : MonoBehaviour {
public float runAwayDistance = 10;
public GameObject targetGO;
private NavMeshAgent navMeshAgent;
void Start() {
navMeshAgent = GetComponent<NavMeshAgent>();
}
void Update() {
Vector3 targetPosition = targetGO.transform.position;
float distanceToTarget = Vector3.Distance(transform.position, targetPosition);
if...