1

I don't know this is a right place to ask this. Because this is a Game development ralated question. I post this question in here (gamedev.stackexchange.com -https://gamedev.stackexchange.com/questions/109190/navmashagent-not-moving) but still no responce. And also post thin in Unity forum (http://answers.unity3d.com/questions/1075904/navmashagent-not-moving-in-unity3d-5.html). Any one here to help me.

Ill post my question here again

Im trying to move a Cube to CheckPoints. FindClosestTarget() method gives closest Checkpoint. 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.

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;
    }

}
Community
  • 1
  • 1
Sajitha Rathnayake
  • 1,688
  • 3
  • 26
  • 47

1 Answers1

0

Make sure the SetActive(false); is happening before you search for the new target, by just putting both lines in the same area.

void OnCollisionEnter (Collision col)
{
    if(col.gameObject.name.Contains("CheckPoint"))
    {
        col.gameObject.SetActive(false);
        Target = FindClosestTarget ().transform;
    }
}
maraaaaaaaa
  • 7,749
  • 2
  • 22
  • 37