How do I make a character run away from the player?
This is a bit of a weird one but if I wanted to have a model that runs away from the player whenever they get close, then stop when the player contacts the model, how would I go about doing that?
So basically it would be like playing tag only when the player tags the model, they would actually pick up the model, if that makes sense.
Also(based on an issue I'm having with a chasing NPC) how do I stop the model from running through physical objects/meshes of buildings, props, etc? I've added a mesh collider to both this model and the other chasing model but they still go through objects P:
Answer by Mraction2012 · Jun 11, 2017 at 04:42 PM
[SerializeField]
private Transform[] navPoints;
[SerializeField]
private Transform player;
[SerializeField]
private UnityEngine.AI.NavMeshAgent agent;
private void Start()
{
if (agent == null)
agent = GetComponent<UnityEngine.AI.NavMeshAgent>();
}
private void Update()
{
RunAwayFromPlayer();
}
void RunAwayFromPlayer()
{
float furthestDistanceSoFar = 0;
Vector3 runPosition = Vector3.zero;
//Check each point
foreach (Transform point in navPoints)
{
print(Vector3.Distance(player.position, point.position));
float currentCheckDistance = Vector3.Distance(player.position, point.position);
if (currentCheckDistance > furthestDistanceSoFar)
{
furthestDistanceSoFar = currentCheckDistance;
runPosition = point.position;
}
}
//Set the right destination for the furthest spot
agent.SetDestination(runPosition);
}
Answer by doublemax · Sep 10, 2016 at 12:29 PM
Use a NavMeshAgent. Nice tutorial here: https://unity3d.com/learn/tutorials/topics/navigation/navigation-overview?playlist=17105Also(based on an issue I'm having with a chasing NPC) how do I stop the model from running through physical objects/meshes of buildings, props, etc?
For the "running away" part: You could have some empty gameobjects spread around your level marked with a special tag, find the one farthest away from the player and then set that spot as the destination for the NavMeshAgent.
Your answer
![](https://koobas.hobune.stream/wayback/20220612092521im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How do I get my AI to chase the player?,How do I go from patrolling to chasing the player? 3 Answers
How do I make an enemy chase the player with a C script? 3 Answers
How to rotate normal map texture 0 Answers
how to check the value of localScale.x? [2D] 0 Answers
Destroy a Prefab from an Array? (C#) 2 Answers