- Home /
no answers
Keep distance using NavMeshAgent causing freeze.
My "teammate" is using NavMeshAgent to follow player. In unity 5.3.2f1(newest) i can set "Stopping distance" but there is no option to set Keep distance (what should be implemented). The way my teammate is kepping distance is bad cause he is just teleporting back (maybe that's the issue) but i think no matter what i put there it will freeze: http://i.imgur.com/7SHLx5o.gif
How to make this to not freeze whole unity?
if (distance < 2)
{
Debug.Log(distance);
distance = 2;
transform.position = (transform.position - target.transform.position).normalized * distance + target.transform.position;
}
Full code:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof (NavMeshAgent))]
public class Teammate : MonoBehaviour {
NavMeshAgent pathfinder;
Transform target;
float distance = 0;
void Start () {
pathfinder = GetComponent<NavMeshAgent> ();
target = GameObject.FindGameObjectWithTag ("Player").transform;
StartCoroutine(UpdatePath());
}
void Update () {
}
IEnumerator UpdatePath()
{
float refreshRate = .25f;
while (target != null)
{
distance = Vector3.Distance(this.transform.position, target.transform.position);
if (distance < 2)
{
Debug.Log(distance);
distance = 2;
transform.position = (transform.position - target.transform.position).normalized * distance + target.transform.position;
}
else {
Vector3 targetPosition = new Vector3(target.position.x, 0, target.position.z);
pathfinder.SetDestination(targetPosition);
yield return new WaitForSeconds(refreshRate);
}
}
}
}
Got an update for follow and flee. It's moving away smoothly but always to the exact same point even if it's randomized ...why ?? With random value, $$anonymous$$mmate is going somewhere near the cube. http://i.imgur.com/67F49DQ.gif
if (distance < 2)
{
Vector3 targetPosition = new Vector3(Random.Range(-10.0F, 10.0F), 0, Random.Range(-10.0F, 10.0F));
targetPosition.Normalize();
pathfinder.SetDestination(targetPosition);
yield return new WaitForSeconds(refreshRate);
}
else
{
Vector3 targetPosition = new Vector3(target.position.x, 0, target.position.z);
pathfinder.SetDestination(targetPosition);
yield return new WaitForSeconds(refreshRate);
}
Follow this Question
Related Questions
Sending an email from my project crashes the unity editor 0 Answers
Why does Unity 2017.3.0f3 crash when NavMeshAgent is scripted to transform.Translate 2 Answers
C# Drag rotation code crashing unity with no errors. 1 Answer
Multiple Cars not working 1 Answer
Unity randomly going unresponsive when importing script changes 0 Answers