防止移动到最近的可能位置

Prevent movement to the nearest possible location

正如您在上图中看到的那样,当我单击白色路径时,对象会完美地移向单击的位置。当我点击蓝色地面时,对象不会移动到那里,但它会在白色路径上找到最近的可能位置,这是我不想要的行为。

如果点击在白色路径之外,我希望对象不移动。

检查员:

白色路径:静态导航 - 可步行

蓝地:无。

对象脚本:

void Update ()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit, 100))
            {
                navAgent.destination = hit.point;
                navAgent.Resume();
            }
        }  
    }

I want the object to not move if the click is outside of the white path.

您可以通过检查单击了哪个对象来做到这一点。您可以使用 hit.collider.name 按名称检查它,或者您可以使用带有 hit.collider.CompareTag 的标签来查看单击了哪个对象。我建议你使用标签。

创建一个名为“whitepath”的标签,然后将您的 whitepath GameObject 设置为该标签。然后您可以在光线投射后比较标签名称。 This 是Unity关于如何创建标签的。

void Update()
{
    if (Input.GetButtonDown("Fire1"))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, 100))
        {
            //Check for white path
            if (hit.collider.CompareTag("whitepath"))
            {
                navAgent.destination = hit.point;
                navAgent.Resume();
            }
        }
    }
}