NavMeshAgent SetDestination acts funny.

I had a scene set as the following picture.

124792-1.png

And a NavMesh baked as the following picture.

124793-2.png

But my “player” (The left-bottom corner sphere) don’t go where I want it want to go!

Test video

Source Codes:

public Camera cam;
public NavMeshAgent agent;
public GameObject particle;
// Update is called once per frame
private void Start()
{
    particle.GetComponent<Renderer>().material.color = Color.red;
}
void Update ()
{
    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = cam.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if(Physics.Raycast(ray,out hit))
        {
            Vector3 v = hit.point;
            agent.SetDestination(v);
            Instantiate(particle,v,transform.rotation);
        }
    }
}

Could somebody please help me out!?

Much appreciated!!!

PS.

I found out through my “particle” that after first few hits, the “hit position” starts to “float”!

That’s why my “particle” became bigger!

It doesn’t “hit” the plane no more!

It always hit at somewhere above the plane!

That’s why my “player” can NOT go to the destination!

Could somebody teach me how to fix it please!

Much appreciated!

I found out that my issue is that the “ray” is NOT always hitting the “plane”!

It always hit some imaginary thing “above” the plane (except the first hit) and I don’t know why!

So to fix the problem, I first assigned a Ground layer to the plane, then add a Public LayerMask lm to the script. Then finally change the Raycast(ray,out hit) to Raycast(ray,out hit, 1000, lm).

And voila! Problem solved!!!

Source Code:

public Camera cam;
public NavMeshAgent agent;
public GameObject particle;
public LayerMask lm;
// Update is called once per frame
private void Start()
{
    particle.GetComponent<Renderer>().material.color = Color.red;
}
void Update ()
{
    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = cam.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if(Physics.Raycast(ray,out hit, 1000, lm))
        {
            Vector3 v = hit.point;
            agent.SetDestination(v);
            Instantiate(particle,v,transform.rotation);
        }
    }
}

PS. Please don’t forget to assign the lm in the inspector to Ground.