- Home /
NavMashAgent not moving in Unity3D 5
Here is my code. Im trying to move a Cube to CheckPoints. FindClosestTarget() method collect all Checkpoints. When Cube hit the CheckPoint, ChackPoint will be Set as Inactive. When the Collision happens FindClosestTarget() call again and get the new closest CheckPoint. Thing is Cube not moving. It Look at the closest check point but not moving. I'm I doing something wrong here?
using UnityEngine;
using System.Collections;
public class EnimyAI03N : MonoBehaviour {
NavMeshAgent agent;
Transform Target;
private float rotationSpeed=15.0f;
void Start () {
agent = GetComponent<NavMeshAgent>();
Target = FindClosestTarget ().transform;
}
void Update ()
{
LookAt (Target);
MoveTo (Target);
}
// Turn to face the player.
void LookAt (Transform T){
// Rotate to look at player.
Quaternion rotation= Quaternion.LookRotation(T.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime*rotationSpeed);
//transform.LookAt(Target); alternate way to track player replaces both lines above.
}
void MoveTo (Transform T){
agent.SetDestination(T.position);
}
void OnCollisionEnter (Collision col)
{
if(col.gameObject.name.Contains("CheckPoint"))
{
Target = FindClosestTarget ().transform;
}
}
GameObject FindClosestTarget() {
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("CheckPoint");
GameObject closest=null;
float distance = Mathf.Infinity;
Vector3 position = transform.position;
foreach (GameObject go in gos) {
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance) {
closest = go;
distance = curDistance;
}
}
return closest;
}
}
Answer by Ziron999 · Oct 04, 2015 at 10:14 AM
Use destination instead of SetDestination in your MoveTo function. Also use Physics sphereoverlap with a filterlayer it will be much more effective then using triggers and easier to control what's going on.
Use overlap sphere to get your target. It has a radius param that can be changed on the fly easily. If target = null expand radius. Then if target radius = 0(or whatever you think the $$anonymous$$imum needs to be) Use a filterlayer to only check for these points.
Thanks for the responce Ziron999. Can you show me how to do it. I still can not make this working. Because Im new to Unity development
There is luckly already hundreds of examples for this here is a link to one.http://answers.unity3d.com/questions/45534/how-is-overlapsphere-used.html
Your answer
![](https://koobas.hobune.stream/wayback/20220612035925im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Navmesh Teleporting (With Server) 1 Answer
How to sample a point on a navMesh Agent path 0 Answers
NavMeshAgent not calculating shortest route. 3 Answers
Make Navmesh Agents more consistent 0 Answers
Enemy follow Camera 0 Answers