2
\$\begingroup\$

I had a scene set as the following picture.

enter image description here

And a NavMesh baked as the following picture.

enter image description here

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

Test vedio

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!

\$\endgroup\$
1
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ That's what I would have recommended. Or use Unitys build in Plane class to perform the raycast as math only. There has to be some invisible collider, maybe the player, maybe your particle effect. \$\endgroup\$ – One Man Monkey Squad Aug 30 '19 at 11:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.